package hy;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.stream.Collector;
public class Solution{
// ab 线程交叉打印
// 该变量可以理解成:上一次打印是否字符A
private volatile boolean flag = false;
public static void main(String[] args) {
Solution so = new Solution();
for(int i=0; i<10; i++){
new Thread(so::printA).start();
new Thread(so::printB).start();
}
}
private synchronized void printA(){
try{
// 判断上一次打印是否 是打印的A,如果是就进行等待,如果不是就执行下面的代码
while(flag){
wait();
}
System.out.println("A");
new Thread().sleep(500);
flag = true;
// 唤醒在等待的线程
notifyAll();
}catch(InterruptedException e){
e.printStackTrace();
}
}
private synchronized void printB(){
try{
// 判断上一次打印是否是打印B,如果是就进行等待,如果不是就执行下面的代码
while(!flag){
wait();
}
System.out.println("B");
new Thread().sleep(500);
flag = false;
notifyAll();
}catch(InterruptedException e){
e.printStackTrace();
}
}
}