多线程经常会接触到线程交互场景,wait和notify、notifyAll就是起到这个作用,三个方法必须要在synchronized锁区域内执行,也就是必须要有当前对象的monitor(锁)。
wait: 阻塞当前线程,交出锁的控制权,等待下一次获取锁继续上次的执行
notify:通知等待当前对象的monitor的线程进行唤醒(注:只能唤醒一个,后续在当前锁区域内的代码还会继续执行)
notifyAll:与notify功能相同,唤醒全部等待当前对象monitor的线程,不过最终还是只有一个被系统选中
以一个示例演示轮流执行A、B、C线程的操作:
package com.healist.coder;
public class ThreadLearn {
public static void main(String[] args) throws InterruptedException {
Object obj1 = new Object();
Object obj2 = new Object();
Object obj3 = new Object();
Thread1 th1 = new Thread1("A", obj3, obj1);
Thread1 th2 = new Thread1("B", obj1, obj2);
Thread1 th3 = new Thread1("C", obj2, obj3);
th1.start();
Thread.sleep(100);
th2.start();
Thread.sleep(100);
th3.start();
}
}
class Thread1 extends Thread {
private String name;
private Object obj1;
private Object obj2;
public Thread1() {}
public Thread1(String name, Object obj1, Object obj2) {
this.name = name;
this.obj1 = obj1;
this.obj2 = obj2;
}
@Override
public void run(){
System.out.println(name + " COME");
int num = 5;
while(num>0) {
synchronized (obj1) {
synchronized (obj2) {
obj2.notify();
num--;
System.out.println(name + " notify");
}
try {
System.out.println(name + " wait");
obj1.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
System.out.println(name + " GO");
}
}
输出结果:
A COME
A notify
A wait
B COME
B notify
B wait
C COME
C notify
C wait
A notify
A wait
B notify
B wait
C notify
C wait
A notify
A wait
B notify
B wait
C notify
C wait
A notify
A wait
B notify
B wait
C notify
C wait
A notify
A wait
B notify
B wait
C notify
C wait
A GO