実装コード:
輸入java.util.concurrent.CountDownLatch。 輸入java.util.concurrent.Semaphore。 パブリック クラスTestABC { 公共 静的 ボイドメイン(文字列[]引数)がスローInterruptedExceptionある{ たCountDownLatchたCountDownLatch = 新しいたCountDownLatch(2 )。 セマフォsemaphoreC =新しいセマフォ(1 ); スレッドスレッドAが = 新しいスレッド(新しいRunnableを(){ @Override 公共 ボイドラン(){ しようと{ Thread.sleep(newjava.util.Random()nextInt( 1000年)); } キャッチ(InterruptedExceptionある電子){ e.printStackTrace(); } のSystem.out.println(にThread.currentThread()のgetName()。)。 countDownLatch.countDown(); } }、 "スレッドA" )。 threadBスレッド = 新しいスレッド(新しいRunnableを(){ @Override 公共 ボイド{実行を() してみてください { )のThread.sleep(newjava.util.Randomを(。nextInt( 1000年)); } キャッチ(InterruptedExceptionある電子){ e.printStackTrace(); } のSystem.out.println(にThread.currentThread()のgetName()。)。 countDownLatch.countDown(); } }、 "スレッドB" )。 threadCスレッド = 新しいスレッド(新しいRunnableを(){ @Override 公共 ボイドラン(){ しようと{ )(semaphoreC.acquireを。 } キャッチ{(例外:InterruptedException eを) e.printStackTrace(); } のSystem.out.println(にThread.currentThread()のgetName()); semaphoreC.release(); } }、 "スレッド-C" ); // A / Bまで占有ロックのCスレッドはCのロックの解除前に、終了した後。 semaphoreC.acquire(); threadA.start(); threadB.start(); threadC.start(); CountDownLatch.await(); // Cスレッドがロックを取得することができるしているので、ロックCを解放 (semaphoreC.release)。 } }