publicvoidfirst(Runnable printFirst)throws InterruptedException { // printFirst.run() outputs "first". Do not change or remove this line. printFirst.run(); semaphore1.release(); // 释放第一个信号量,允许第二个线程执行 }
publicvoidsecond(Runnable printSecond)throws InterruptedException { semaphore1.acquire(); // 等待第一个线程完成 // printSecond.run() outputs "second". Do not change or remove this line. printSecond.run(); semaphore2.release(); // 释放第二个信号量,允许第三个线程执行 }
publicvoidthird(Runnable printThird)throws InterruptedException { semaphore2.acquire(); // 等待第二个线程完成 // printThird.run() outputs "third". Do not change or remove this line. printThird.run(); semaphore2.release(); // 释放第三个信号量,允许其他线程执行 } }
// printFirst.run() outputs "first". Do not change or remove this line. try { printFirst.run(); } finally { firstLatch.countDown(); } }
publicvoidsecond(Runnable printSecond)throws InterruptedException { firstLatch.await(); try { // printSecond.run() outputs "second". Do not change or remove this line. printSecond.run(); } finally { secondLatch.countDown(); } }
publicvoidthird(Runnable printThird)throws InterruptedException { secondLatch.await(); // printThird.run() outputs "third". Do not change or remove this line. printThird.run();