简介
说说 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