privateboolean isFooTurn = true; private Object obj = new Object();
publicFooBar(int n){ this.n = n; }
publicvoidfoo(Runnable printFoo)throws InterruptedException { for (int i = 0; i < n; i++) { synchronized (obj){ if (!isFooTurn){ obj.wait(); } // printFoo.run() outputs "foo". Do not change or remove this line. printFoo.run(); isFooTurn = false; obj.notifyAll(); } } }
publicvoidbar(Runnable printBar)throws InterruptedException { for (int i = 0; i < n; i++) { synchronized (obj){ if (isFooTurn){ obj.wait(); } // printBar.run() outputs "bar". Do not change or remove this line. printBar.run(); isFooTurn = true; obj.notifyAll(); } } } }
publicvoidfoo(Runnable printFoo)throws InterruptedException { for (int i = 0; i < n; i++) { lock.lock(); try { while (!allowedAProcess) { conditionA.await(); } // printFoo.run() outputs "foo". Do not change or remove this line. printFoo.run(); allowedAProcess = false; conditionB.signalAll(); } finally { lock.unlock(); } } }
publicvoidbar(Runnable printBar)throws InterruptedException { for (int i = 0; i < n; i++) { lock.lock(); try { while (allowedAProcess) { conditionB.await(); } // printBar.run() outputs "bar". Do not change or remove this line. printBar.run();