本帖最后由 吃阁子的猫 于 2013-9-13 14:20 编辑
class Print{
private int flat = 1;
public synchronized void print1() throws Exception{
while (flat!=1) {
wait();
}
System.out.print("传");
System.out.print("智");
System.out.print("播");
System.out.print("客");
System.out.println();
notifyAll();
flat = 2;
}
public synchronized void print2() throws Exception{
while (flat!=2) { //即使再判断,也是让本线程等待,其他2个都被唤醒,不也是随机执行一个线程吗,与用 if 判断有什么区别呢?
wait();
}
System.out.print("黑");
System.out.print("马");
System.out.print("程");
System.out.print("序");
System.out.print("员");
System.out.println();
notifyAll();
flat = 3;
}
public synchronized void print3() throws Exception{
while (flat!=3) {
wait();
}
System.out.print("c");
System.out.print("s");
System.out.print("d");
System.out.print("n");
System.out.println();
notifyAll();
flat = 1;
}
} |
|