简介
说说 sleep() 方法和 wait() 方法区别和共同点?
两者最主要的区别在于:sleep() 方法没有释放锁,而 wait() 方法释放了锁 。
两者都可以暂停线程的执行。
wait() 通常被用于线程间交互/通信,sleep() 通常被用于暂停执行。
wait() 方法被调用后,线程不会自动苏醒,需要别的线程调用同一个对象上的 notify() 或者 notifyAll() 方法。sleep() 方法执行完成后,线程会自动苏醒。或者可以使用 wait(long timeout) 超时后线程会自动苏醒。
原码注解
Causes the currently executing thread to sleep (temporarily cease execution) for the
specified number of milliseconds, subject to the precision and accuracy of system
timers and schedulers. The thread does not lose ownership of any monitors.
证明
public static void main(String[] args) {
Object lock = new Object();
ExecutorService executorService = Executors.newCachedThreadPool();
Runnable runnable = new Runnable() {
@Override
public void run() {
synchronized (lock){
//给共享对象lock加锁
try {
System.out.println(Thread.currentThread().getName() + "获取锁进来了");
TimeUnit.SECONDS.sleep(5);
System.out.println(Thread.currentThread().getName() + "释放锁出来了");
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
};
for (int i = 0; i < 5; i++) {
//启动五个线程执行
executorService.execute(runnable);
}
}
控制台:
pool-1-thread-1获取锁进来了
pool-1-thread-1释放锁出来了
pool-1-thread-5获取锁进来了
pool-1-thread-5释放锁出来了
pool-1-thread-4获取锁进来了
pool-1-thread-4释放锁出来了
pool-1-thread-3获取锁进来了
pool-1-thread-3释放锁出来了
pool-1-thread-2获取锁进来了
pool-1-thread-2释放锁出来了
Process finished with exit code 0
本文详细介绍了Java中sleep()方法和wait()方法的区别。sleep()方法不会释放锁,而wait()方法会释放锁,使得其他线程有机会获得锁。wait()需要与其他线程协作,通过notify()或notifyAll()唤醒。在示例代码中展示了多个线程如何交替获取并释放锁,体现了两者在线程同步中的不同作用。

9102

被折叠的 条评论
为什么被折叠?



