logo

CountDownLatch Java

CountDownLatch tiek izmantots, lai pārliecinātos, ka uzdevums pirms tā sākšanas gaida citus pavedienus. Lai saprastu tā pielietojumu, apskatīsim serveri, kurā galvenais uzdevums var sākties tikai tad, kad ir sākti visi nepieciešamie pakalpojumi. CountDownLatch darbība: Kad mēs izveidojam CountDownLatch objektu, mēs norādām pavedienu skaitu, kam jāgaida, līdz visi šie pavedieni ir jāveic, izsaucot CountDownLatch.countDown(), kad tie ir pabeigti vai gatavi darbam. Tiklīdz skaits sasniedz nulli, gaidīšanas uzdevums sāk darboties. CountDownLatch piemērs JAVA: 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();  }  } } 
Izvade:
WORKER-1 finished WORKER-2 finished WORKER-3 finished WORKER-4 finished main has finished 
Fakti par CountDownLatch:
  1. CountDownLatch objekta izveide, nododot int tā konstruktoram (skaits), faktiski ir pasākuma uzaicināto pušu (pavedienu) skaits.
  2. Pavediens, kura apstrāde ir atkarīga no citiem pavedieniem, gaida, līdz katrs cits pavediens izsauc atskaiti. Visi pavedieni, kas gaida await(), turpinās kopā, tiklīdz skaitīšana sasniedz nulli.
  3. Metode countDown() samazina skaitu un gaida() metodes blokus līdz count == 0