欢迎来到尧图网

客户服务 关于我们

您的位置:首页 > 新闻 > 资讯 > sleep 和 wait区别

sleep 和 wait区别

2024/10/25 12:22:15 来源:https://blog.csdn.net/wdwwx/article/details/140156963  浏览:    关键词:sleep 和 wait区别
特性wait()sleep()
所在类和定义Object类中的实例方法Thread类中的静态方法
释放锁是,调用wait()会释放当前持有的对象锁否,调用sleep()不会释放任何锁
使用场景线程间通信,通常与notify()notifyAll()配合使用让线程暂停执行一段时间,通常用于模拟延迟或调度任务
唤醒机制依赖其他线程调用notify()notifyAll()自动唤醒,经过指定时间后继续执行
抛出的异常InterruptedExceptionIllegalMonitorStateExceptionInterruptedException
必须在同步块中调用是,必须在synchronized块中调用否,不需要在synchronized块中调用

示例代码

wait() 示例代码

public class WaitExample {private static final Object lock = new Object();public static void main(String[] args) {Thread thread1 = new Thread(() -> {synchronized (lock) {try {System.out.println("Thread 1 is waiting.");lock.wait();System.out.println("Thread 1 is resumed.");} catch (InterruptedException e) {e.printStackTrace();}}});Thread thread2 = new Thread(() -> {synchronized (lock) {try {Thread.sleep(2000);System.out.println("Thread 2 is notifying.");lock.notify();} catch (InterruptedException e) {e.printStackTrace();}}});thread1.start();thread2.start();}
}

sleep() 示例代码

public class SleepExample {public static void main(String[] args) {Thread thread = new Thread(() -> {try {System.out.println("Thread is sleeping for 2 seconds.");Thread.sleep(2000);System.out.println("Thread is awake.");} catch (InterruptedException e) {e.printStackTrace();}});thread.start();}
}

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com