logo

JavaのCountDownLatch

CountDownLatch は、タスクが開始する前に他のスレッドを待機するようにするために使用されます。その応用を理解するために、必要なサービスがすべて開始された場合にのみメインタスクが開始できるサーバーを考えてみましょう。 CountDownLatch の動作: CountDownLatch のオブジェクトを作成するとき、すべてのスレッドが完了するかジョブの準備ができたら CountDownLatch.countDown() を呼び出してカウントダウンする必要があるすべてのスレッドが待機するスレッドの数を指定します。カウントがゼロになるとすぐに、待機中のタスクが実行を開始します。 JAVA での CountDownLatch の例: Java
// Java Program to demonstrate how  // to use CountDownLatch Its used  // when a thread needs to wait for other  // threads before starting its work. import java.util.concurrent.CountDownLatch; public class CountDownLatchDemo {  public static void main(String args[])   throws InterruptedException  {  // Let us create task that is going to   // wait for four threads before it starts  CountDownLatch latch = new CountDownLatch(4);  // Let us create four worker   // threads and start them.  Worker first = new Worker(1000 latch   'WORKER-1');  Worker second = new Worker(2000 latch   'WORKER-2');  Worker third = new Worker(3000 latch   'WORKER-3');  Worker fourth = new Worker(4000 latch   'WORKER-4');  first.start();  second.start();  third.start();  fourth.start();  // The main task waits for four threads  latch.await();  // Main thread has started  System.out.println(Thread.currentThread().getName() +  ' has finished');  } } // A class to represent threads for which // the main thread waits. class Worker extends Thread {  private int delay;  private CountDownLatch latch;  public Worker(int delay CountDownLatch latch  String name)  {  super(name);  this.delay = delay;  this.latch = latch;  }  @Override  public void run()  {  try  {  Thread.sleep(delay);  latch.countDown();  System.out.println(Thread.currentThread().getName()  + ' finished');  }  catch (InterruptedException e)  {  e.printStackTrace();  }  } } 
出力:
WORKER-1 finished WORKER-2 finished WORKER-3 finished WORKER-4 finished main has finished 
CountDownLatch に関する事実:
  1. int をコンストラクターに渡して CountDownLatch のオブジェクトを作成すると (カウント)、実際にはイベントの招待されたパーティー (スレッド) の数になります。
  2. 他のスレッドに依存して処理を開始するスレッドは、他のすべてのスレッドがカウントダウンを呼び出すまで待機します。 await() を待機しているすべてのスレッドは、カウントダウンが 0 に達すると一緒に処理を進めます。
  3. countDown() メソッドは、count == 0 になるまで count および await() メソッドのブロックをデクリメントします。