题目
示例
方法一:synchronize+wait/notifyAlljava
具体代码web
class Foo { private int flag = 1; private Object lock = new Object(); public Foo() { } public void first(Runnable printFirst) throws InterruptedException { synchronized(lock){ while(flag != 1){ lock.wait(); } // printFirst.run() outputs "first". Do not change or remove this line. printFirst.run(); flag = 2; lock.notifyAll(); } } public void second(Runnable printSecond) throws InterruptedException { synchronized(lock){ while(flag != 2){ lock.wait(); } // printSecond.run() outputs "second". Do not change or remove this line. printSecond.run(); flag = 3; lock.notifyAll(); } } public void third(Runnable printThird) throws InterruptedException { synchronized(lock){ while(flag != 3){ lock.wait(); } // printThird.run() outputs "third". Do not change or remove this line. printThird.run(); flag = 1; lock.notifyAll(); } } }
方法二:CountDownLatchsvg
class Foo { final CountDownLatch latch1 = new CountDownLatch(1); final CountDownLatch latch2 = new CountDownLatch(1); public Foo() { } public void first(Runnable printFirst) throws InterruptedException { // printFirst.run() outputs "first". Do not change or remove this line. printFirst.run(); latch1.countDown(); } public void second(Runnable printSecond) throws InterruptedException { latch1.await(); // printSecond.run() outputs "second". Do not change or remove this line. printSecond.run(); latch2.countDown(); } public void third(Runnable printThird) throws InterruptedException { latch2.await(); // printThird.run() outputs "third". Do not change or remove this line. printThird.run(); } }
方法三:Semaphoreui
class Foo { Semaphore semaphore1 = new Semaphore(0); Semaphore semaphore2 = new Semaphore(0); public Foo() { } public void first(Runnable printFirst) throws InterruptedException { // printFirst.run() outputs "first". Do not change or remove this line. printFirst.run(); semaphore1.release(); } public void second(Runnable printSecond) throws InterruptedException { semaphore1.acquire(); // printSecond.run() outputs "second". Do not change or remove this line. printSecond.run(); semaphore2.release(); } public void third(Runnable printThird) throws InterruptedException { semaphore2.acquire(); // printThird.run() outputs "third". Do not change or remove this line. printThird.run(); } }