下面是代码实例
1 public class WaitDemo implements Runnable { 2 3 private Object lock; 4 5 public WaitDemo(Object lock) { 6 this.lock = lock; 7 } 8 9 @Override 10 public void run() { 11 synchronized (lock) { 12 System.out.println("Begin wait() ThreadName=" + Thread.currentThread().getName()); 13 try { 14 // [STEP-1] WaitDemo线程立刻释放获得的对象锁lock,并放弃CPU,进入等待队列。 15 lock.wait(); 16 } catch (InterruptedException e) { 17 e.printStackTrace(); 18 } 19 // [STEP-4] WaitDemo有机会获得另一个线程释放的锁,并从等待的地方起开始执行。 20 System.out.println("End wait() ThreadName=" + Thread.currentThread().getName()); 21 } 22 } 23 }
1 public class NotifyDemo implements Runnable { 2 3 private Object lock; 4 5 public NotifyDemo(Object lock) { 6 this.lock = lock; 7 } 8 9 @Override 10 public void run() { 11 synchronized (lock) { 12 System.out.println("Begin notify() ThreadName=" + Thread.currentThread().getName()); 13 // [STEP-2] NotifyDemo线程唤醒其他挂起的线程(WaitDemo线程)。但是此时它并不立即释放锁。 14 lock.notify(); 15 try { 16 System.out.println("Sleep 3s..."); 17 Thread.sleep(3000); 18 } catch (InterruptedException e) { 19 e.printStackTrace(); 20 } 21 System.out.println("End notify() ThreadName=" + Thread.currentThread().getName()); 22 // [STEP-3] 释放锁。 23 } 24 } 25 }
1 // 该实例无法保证假设在线程WaitDemo和NotifyDemo的先后执行顺序。如果线程B先执行了notify()然后结束了,线程A才去执行wait(),那此时,线程A将无法被正常唤醒了 2 public class DemoTest { 3 4 public static void main(String[] args) throws InterruptedException { 5 Object o = new Object(); 6 // WaitDemo 7 Thread a = new Thread(new WaitDemo(o)); 8 a.setName("WaitDemo"); 9 a.start(); 10 Thread.sleep(2000); 11 // NotifyDemo 12 Thread b = new Thread(new NotifyDemo(o)); 13 b.setName("NotifyDemo"); 14 b.start(); 15 } 16 }