实例
package com.example.demo.thread;public class WaitTest {
public static Object lock = new Object();public static void main(String[] args) throws InterruptedException {
WaitThread1 waitThread1 = new WaitThread1();WaitThread2 waitThread2 = new WaitThread2();WaitThread3 waitThread3 = new WaitThread3();waitThread1.setName("waitThread1");waitThread1.start();waitThread2.setName("waitThread2");waitThread2.start();waitThread3.setName("waitThread2");waitThread3.start();}}class WaitThread1 extends Thread {
public void run() {
synchronized (WaitTest.lock) {
System.out.println("start" + Thread.currentThread().getName());try {
WaitTest.lock.wait();} catch (InterruptedException e) {
e.printStackTrace();}}System.out.println("end" + Thread.currentThread().getName());
// Thread.sleep(2000);System.out.println("WaitThread1");}
}class WaitThread2 extends Thread {
public void run() {
synchronized (WaitTest.lock) {
System.out.println("start" + Thread.currentThread().getName());try {
WaitTest.lock.wait();} catch (InterruptedException e) {
e.printStackTrace();}}System.out.println("end" + Thread.currentThread().getName());System.out.println("WaitThread2");}
}class WaitThread3 extends Thread {
public void run() {
synchronized (WaitTest.lock) {
System.out.println("start" + Thread.currentThread().getName());
// WaitTest.lock.notify();
// WaitTest.lock.notify(); // 如果只调用一次notify()那么只有一个线程会继续执行WaitTest.lock.notifyAll(); // 所有持有WaitTest.lock的线程都会重新到就绪态}System.out.println("end" + Thread.currentThread().getName());System.out.println("WaitThread3");}
}
输出
startwaitThread1
startwaitThread2
startwaitThread2
endwaitThread2
endwaitThread2
WaitThread2
endwaitThread1
WaitThread1
WaitThread3
从输出结果看,wait会释放锁,并等待唤醒,notify()会导致线程重新进入就绪态,notifyAll()会将所有持有当前锁的线程编程就绪态