JAVA中的wait和notify

 1 package com.runnabledemo;
 2 
 3 public class waitnotifydemo01 {
 4     public static void main(String[]args)throws Exception {
 5         final Object obj = new Object();
 6         Thread t1 = new Thread() {
 7             public void run() {
 8                 synchronized (obj) {
 9                     try {
10                         obj.wait();
11                         System.out.println("Thread 1 wake up.");
12                     } catch (InterruptedException e) {
13                     }
14                 }
15             }
16         };
17         t1.start();
18         Thread.sleep(1000);//We assume thread 1 must start up within 1 sec.
19         Thread t2 = new Thread() {
20             public void run() {
21                 synchronized (obj) {
22                     obj.notifyAll();
23                     System.out.println("Thread 2 sent notify.");
24                 }
25             }
26         };
27         t2.start();
28     }
29 }

输出结果为:

Thread 2 sent notify.
Thread 1 wake up.

分析:t1 启动后执行 obj.wait() 时,进入阻塞状态,让出时间片并释放锁,等待其他线程的唤醒。然后 t2 获取到 obj,并唤醒 t1,待 t2 执行完毕,释放锁后,t1 再继续执行。

notify()就是对对象锁的唤醒操作。但有一点需要注意的是notify()调用后,并不是马上就释放对象锁的,而是在相应的synchronized(){}语句块执行结束,自动释放锁后,JVM会在wait()对象锁的线程中随机选取一线程,赋予其对象锁,唤醒线程,继续执行。这样就提供了在线程间同步、唤醒的操作。

原文地址:https://www.cnblogs.com/XuGuobao/p/7208639.html