本文可以结合 Java 关键字 synchronized 总结 一起理解。
wait():交出锁和 CPU 控制权,线程进入阻塞状态,等待 notify() 唤醒;
notify():等线程交出锁(synchronized 代码块执行完毕 / 执行 wait())后,唤醒一个 wait();
notifyAll():等线程交出锁(synchronized 代码块执行完毕 / 执行 wait())后,唤醒所有 wait();
范例代码:
Integer i = new Integer(4);
new Thread(new Runnable() {
public void run() {
synchronized (i) {
System.out.println("1号线程,wait 前");
try {
// 交出 i 的对象锁,进入阻塞,等待 notify() 唤醒
i.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("1号线程,wait 后");
}
}
}).start();
new Thread(new Runnable() {
public void run() {
synchronized (i) {
System.out.println("2号线程,wait 前");
try {
// 交出 i 的对象锁,进入阻塞,等待 notify() 唤醒
i.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("2号线程,wait 后");
}
}
}).start();
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
new Thread(new Runnable() {
public void run() {
synchronized (i) {
System.out.println("3号线程,notify all");
// 线程交出 i 的对象锁(synchronized 代码块执行完毕)后,唤醒所有的 wait()
i.notifyAll();
}
}
}).start();