package org.example.juclearning.learning02;
public class TT {
public static void main(String[] args) {
WaitAndNofity wan = new WaitAndNofity(1);
new Thread(){
@Override
public void run() {
try {
wan.print("a",1,2);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
}
}.start();
new Thread(){
@Override
public void run() {
try {
wan.print("b",2,3);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
}
}.start();
new Thread(){
@Override
public void run() {
try {
wan.print("c",3,1);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
}
}.start();
}
}
class WaitAndNofity{
int flag;
public WaitAndNofity(int flag) {
this.flag = flag;
}
public void print(String str, int currentFlag, int nextFlag) throws InterruptedException {
for (int i = 0; i < 5; i++) {
synchronized (this){
while(flag != currentFlag){
this.wait();
}
System.out.print(str);
flag = nextFlag;
this.notifyAll();
}
}
}
}
对于WaitAndNofify这个类作出如下说明
分析交替打印abc这个问题,假设利用线程1,2,3份分别打印a,b,c显然,需要一个标志为,使得三个线程可以执行到自己的时候可以执行打印,而其他线程进行休眠。此外,在打印完成后,需要让执行结束的线程去通知下一个线程进行打印。
观察代码的49行-51行,当共享的标志为对象和当前输入的标记为不符合的时候,这个线程就会进入阻塞状态。
当共享标记位和当前输入的标记为符合的时候,执行打印操作,同时将标志为改为下一个,使得下一个线程能够正常执行。