public class PrintABC {
private int state;
private int count;
private static final int MAX_COUNT = 50;
public synchronized void printLetter(String letter, int targetState) {
while (state != targetState) {
try {
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.print(letter);
state = (state + 1) % 3;
count++;
if (count == MAX_COUNT) {
System.exit(0);
}
notifyAll();
}
public static void main(String[] args) {
PrintABC printABC = new PrintABC();
new Thread(() -> {
while (printABC.count < MAX_COUNT) {
printABC.printLetter("A", 0);
}
}).start();
new Thread(() -> {
while (printABC.count < MAX_COUNT) {
printABC.printLetter("B", 1);
}
}).start();
new Thread(() -> {
while (printABC.count < MAX_COUNT) {
printABC.printLetter("C", 2);
}
}).start();
}
}
该代码使用一个共享的状态state
,来控制3个线程按顺序交替打印"A","B"和"C"。每个线程在运行时会检查当前的state
值,如果值不符合该线程打印的字符,则线程会进入等待状态。当状态值与线程打印的字符相同时,线程会打印字符,并通知其他线程来唤醒等待。在打印完指定次数后,程序通过调用System.exit()
方法来结束程序。