7.6.1 基本的差别
- sleep 是 Thread 类的方法,wait 是 Object 类中定义的方法



- sleep() 方法可以在任何地方使用
wait() 方法只能在 synchronized 方法或 synchronized 块中使用
7.6.2 最主要的本质区别
Thread.sleep 只会让出 CPU,不会导致锁行为的改变
如果当前线程是拥有锁的,那么 Thread.sleep 不会让线程释放锁,而只会主动让出 CPU,这样 CPU 就可以执行其他任务。- Object.wait 不仅让出 CPU,还会释放已经占有的同步资源锁
下面看一个示例。
- 编写一个类,创建两个线程,第一个线程执行 wait 逻辑,第二个线程执行 sleep 逻辑 ```java package thread;
public class WaitSleepDemo { public static void main(String[] args) { final Object lock = new Object(); new Thread(new Runnable() { @Override public void run() { System.out.println(“thread A is waiting to get lock”); synchronized (lock) { try { System.out.println(“thread A get lock”); Thread.sleep(20); System.out.println(“thread A do wait method”); lock.wait(1000); System.out.println(“thread A is done”); } catch (InterruptedException e) { e.printStackTrace(); } } } }).start(); try { // 由于这两个线程执行顺序不定,为了保证第一个线程先执行 Thread.sleep(10); } catch (InterruptedException e) { e.printStackTrace(); } new Thread(new Runnable() { @Override public void run() { System.out.println(“thread B is waiting to get lock”); synchronized (lock) { try { System.out.println(“thread B get lock”); System.out.println(“thread B is sleeping 10 ms”); Thread.sleep(20); System.out.println(“thread B is done”); } catch (InterruptedException e) { e.printStackTrace(); } } } }).start(); } }
2. 调换逻辑```javapackage thread;public class WaitSleepDemo {public static void main(String[] args) {final Object lock = new Object();new Thread(new Runnable() {@Overridepublic void run() {System.out.println("thread A is waiting to get lock");synchronized (lock) {try {System.out.println("thread A get lock");Thread.sleep(20);System.out.println("thread A do wait method");Thread.sleep(20);System.out.println("thread A is done");} catch (InterruptedException e) {e.printStackTrace();}}}}).start();try {Thread.sleep(10);} catch (InterruptedException e) {e.printStackTrace();}new Thread(new Runnable() {@Overridepublic void run() {System.out.println("thread B is waiting to get lock");synchronized (lock) {try {System.out.println("thread B get lock");System.out.println("thread B is sleeping 10 ms");lock.wait(1000);System.out.println("thread B is done");} catch (InterruptedException e) {e.printStackTrace();}}}}).start();}}

可以看出 wait 方法必须写在 synchronized 中,只有获取锁才能释放锁。
