classFoo{private Semaphore first =newSemaphore(1);private Semaphore second =newSemaphore(0);private Semaphore third =newSemaphore(0);publicFoo(){}publicvoidfirst(Runnable printFirst)throws InterruptedException {// printFirst.run() outputs "first". Do not change or remove this line.
first.acquire();
printFirst.run();
second.release();}publicvoidsecond(Runnable printSecond)throws InterruptedException {// printSecond.run() outputs "second". Do not change or remove this line.
second.acquire();
printSecond.run();
third.release();}publicvoidthird(Runnable printThird)throws InterruptedException {// printThird.run() outputs "third". Do not change or remove this line.
third.acquire();
printThird.run();
first.release();}}
解法二 CountDownLatch
classFoo{private CountDownLatch second =newCountDownLatch(1);private CountDownLatch third =newCountDownLatch(1);publicFoo(){}publicvoidfirst(Runnable printFirst)throws InterruptedException {// printFirst.run() outputs "first". Do not change or remove this line.
printFirst.run();
second.countDown();}publicvoidsecond(Runnable printSecond)throws InterruptedException {// printSecond.run() outputs "second". Do not change or remove this line.
second.await();
printSecond.run();
third.countDown();}publicvoidthird(Runnable printThird)throws InterruptedException {// printThird.run() outputs "third". Do not change or remove this line.
third.await();
printThird.run();}}
解法三 synchronized
classFoo{privateboolean first =false;privateboolean second =false;privatestatic Object lock =newObject();publicFoo(){}publicvoidfirst(Runnable printFirst)throws InterruptedException {synchronized(lock){// printFirst.run() outputs "first". Do not change or remove this line.
printFirst.run();
first =true;
lock.notifyAll();}}publicvoidsecond(Runnable printSecond)throws InterruptedException {synchronized(lock){while(!first){
lock.wait();}// printSecond.run() outputs "second". Do not change or remove this line.
printSecond.run();
second =true;
lock.notifyAll();}}publicvoidthird(Runnable printThird)throws InterruptedException {synchronized(lock){while(!second){
lock.wait();}// printThird.run() outputs "third". Do not change or remove this line.
printThird.run();}}}
leetcode 1114:按需打印解法一:Semaphoreclass Foo { private Semaphore first = new Semaphore(1); private Semaphore second = new Semaphore(0); private Semaphore third = new Semaphore(0); public Foo() { } public void first(Runnable