public class Zuoye6 {
public static void main(String[] args) {
//打印A的线程
PrintThread a = new PrintThread(0,'A',1);
//打印B的线程
PrintThread b = new PrintThread(1,'B',2);
//打印C的线程
PrintThread c = new PrintThread(2,'C',0);
a.start();
b.start();
c.start();
}
}
/**打印任务*/
class PrintThread extends Thread{
/**当前状态*/
private int currentState;
/**打印字符*/
private char printChar;
/**下一个状态*/
private int nextState;
/**默认状态*/
private static int state = 0;
/**锁对象*/
private static Object lock = new Object();
public PrintThread(int currentState, char printChar, int nextState) {
this.currentState = currentState;
this.printChar = printChar;
this.nextState = nextState;
}
@Override
public void run() {
for(int i=0;i<20;i++) {
synchronized (lock) {
while(currentState!=state) {
try {
lock.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.print(printChar);
//将状态切换到下一个
state = nextState;
//通知其他处于阻塞状态线程
lock.notifyAll();
}
}
}
}