public class ABCInfinite{
//标志位 0-> a 1-> b 2-> c
private static int flag = 0;
private static int count = 0;//已输出的"abc"数组
private static final int TARGET = 10;//目标次数大于5
//锁对象,保证线程同步
private static final Object lock = new Object();
public static void main(string[]args){
//线程A负责输出a
Thread threadA = new Thread(() -> {
while(count<TARGET){//无限循环
synchronized(lock){
//等待标志位为0,轮到自己输出
while(flag != 0 && count < TARGET){
try{
lock.wait();
catch(InterruptedException e){
Thread.currentThread().interrupt();
return;
}
}
}
if(count >= TARGET)break;//达到次数,退出
System.out.print("a");
flag = 1;//下一轮输出到b
lock.notifyAll();
}
}
,"thread-A"}
//线程B负责输出b
Thread threadB = new Thread(() -> {
while(count < TARGET){//无限循环
synchronized(lock){
//等待标志位为1,轮到自己输出
while(flag != 1 && count < TARGET){
try{
lock.wait();
catch(InterruptedException e){
Thread.currentThread().interrupt();
return;
}
}
}
if(count>=TARGET)break;
System.out.print("b");
flag = 2;//下一轮输出到c
lock.notifyAll();
}
}
,"thread-B"}
//线程C负责输出c
Thread threadC = new Thread(() -> {
while(count < TARGET){//无限循环
synchronized(lock){
//等待标志位为2,轮到自己输出
while(flag != 2 && count < TARGET){
try{
lock.wait();
catch(InterruptedException e){
Thread.currentThread().interrupt();
return;
}
}
}
if(count>=TARGET)break;
System.out.print("c");
count++;
flag = 0;//一轮结束,回到输出a
lock.notifyAll();
}
}
,"thread-C"}
threadA.start();
threadB.start();
threadC.start();
}
}