public class TestJUC6{
public static void main(String[] args){
//初始化次数为10
Print print=new Print(10);
//C线程
new Thread(()->{
try {
print.printC();
} catch (InterruptedException e) {
e.printStackTrace();
}
},"C").start();
//B线程
new Thread(()->{
try {
print.printB();
} catch (InterruptedException e) {
e.printStackTrace();
}
},"B").start();
//A线程
new Thread(()->{
try {
print.printA();
} catch (InterruptedException e) {
e.printStackTrace();
}
},"A").start();
}
}
//打印类
class Print{
int num=0;//循环次数
int NotifyFlag=1; //1=A,2=B,3=C
Print(int i){
this.num=i;
}
public synchronized void printA() throws InterruptedException {
int i=num;
while(i>0){
if(NotifyFlag==1){
System.out.println("A");
i--;
NotifyFlag=2;
this.notifyAll();
}else{
this.wait();
}
}
}
public synchronized void printB() throws InterruptedException {
int i=num;
while(i>0){
if(NotifyFlag==2){
System.out.println("B");
i--;
NotifyFlag=3;
this.notifyAll();
}else{
this.wait();
}
}
}
public synchronized void printC() throws InterruptedException {
int i=num;
while(i>0){
if(NotifyFlag==3){
System.out.println("C");
i--;
NotifyFlag=1;
this.notifyAll();
}else{
this.wait();
}
}
}
}