三个线程交替打印ABC,用到线程的通知机制:用一个共享变量来表示当前需要打印的线程
index 0打印A,然后将index修改为1,然后打印B,将index修改为2,打印C,然后将index修改为0
判断等待,业务处理(就是打印和修改index),唤醒等待
package cn.yishijie;
/**
* 交替打印AB 10次
*/
public class ThreadNotify {
public static void main(String[] args) {
AB ab = new AB();
new Thread(()->{
for (int i =0;i<10;i++){
ab.printA();
}
}).start();
new Thread(()->{
for (int i =0;i<10;i++){
ab.printB();
}
}).start();
new Thread(()->{
for (int i =0;i<10;i++){
ab.printC();
}
}).start();
}
}
class AB{
private int index;
public synchronized void printA(){
// 这里一定用while,防止虚假唤醒
while (index != 0){
try {
th