public class WaitSleepDemo { public static void main(String[] args) { Object lock = new Object(); new Thread(new Runnable() { @Override public void run() { System.out.println("Thread A is waiting to get lock"); synchronized (lock) { System.out.println("Thread A get lock"); try { Thread.sleep(20); System.out.println("Thread A do wait method"); //线程 A 释放锁,此时线程 B 可以拿到锁,进入 synchronized 代码块 lock.wait(1000); //这一句代码会阻塞,直到线程 B 完成后会释放锁,此时线程 A 拿到锁,执行这一句 System.out.println("Thread A is done"); } catch (Exception e) { e.printStackTrace(); } } } }).start();
//睡眠 20ms 后,在启动 B 线程,此时线程 A 已经获取了锁 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"); //线程 B 阻塞在这里,直到线程 A 执行 lock.wait(1000); 时,线程 B 才继续往下执行 synchronized (lock) {
System.out.println("Thread B get lock"); try { System.out.println("Thread B is sleep"); Thread.sleep(10); lock.notifyAll(); //这里调用 yield() 方法不会让出 CPU,直到该线程执行完成释放锁才会让出 CPU Thread.yield(); Thread.sleep(2000); System.out.println("Thread B is Done");