privateboolean firstDone; privateboolean secondDone; private Object lock = new Object();
publicFoo(){}
publicvoidfirst(Runnable printFirst)throws InterruptedException { synchronized(lock) { // printFirst.run() outputs "first". Do not change or remove this line. printFirst.run(); firstDone = true; lock.notifyAll(); } }
publicvoidsecond(Runnable printSecond)throws InterruptedException { synchronized(lock) { while (!firstDone) lock.wait(); // printSecond.run() outputs "second". Do not change or remove this line. printSecond.run(); secondDone = true; lock.notifyAll(); } }
publicvoidthird(Runnable printThird)throws InterruptedException { synchronized(lock) { while (!secondDone) lock.wait(); // printThird.run() outputs "third". Do not change or remove this line. printThird.run(); } } }
publicvoidfirst(Runnable printFirst)throws InterruptedException { // printFirst.run() outputs "first". Do not change or remove this line. printFirst.run(); firstJobDone=true; }
publicvoidsecond(Runnable printSecond)throws InterruptedException { while (!firstJobDone){ // 等待printFirst完成 } // printSecond.run() outputs "second". Do not change or remove this line. printSecond.run(); secondJobDone=true; }
publicvoidthird(Runnable printThird)throws InterruptedException { while (!secondJobDone){ // 等待printSecond完成 } // printThird.run() outputs "third". Do not change or remove this line. printThird.run(); } }