代碼如下:
有陷阱漠另,有意者請分析
public class PrintABCByOrder {
private static final Object object = new Object();
public static void main(String[] args) {
OrderThread A = new OrderThread(1, "A");
OrderThread B = new OrderThread(2, "B");
OrderThread C = new OrderThread(3, "C");
A.start();
B.start();
C.start();
OrderThread.count ++;
}
private static class OrderThread extends Thread {
volatile static int count;
int order;
String message;
OrderThread(int order, String message) {
this.order = order;
this.message = message;
}
@Override
public void run() {
synchronized (object) {
while (count != this.order) {
try {
object.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println(message);
count++;
object.notifyAll();
}
}
}
}