Java by API/java.util.concurrent/CountDownLatch — различия между версиями

Материал из Java эксперт
Перейти к: навигация, поиск
м (1 версия)
 
(нет различий)

Версия 17:43, 31 мая 2010

CountDownLatch: await()

 
import java.util.concurrent.CountDownLatch;
   
public class Main {
  public static void main(String args[]) {
    CountDownLatch cdl = new CountDownLatch(5);
    new MyThread(cdl);
   
    try {
      cdl.await();
    } catch (InterruptedException exc) {
      System.out.println(exc);
    }
    System.out.println("Done");
  }
}
   
class MyThread implements Runnable {
  CountDownLatch latch;
   
  MyThread(CountDownLatch c) {
    latch = c;
    new Thread(this).start();
  }
   
  public void run() {
    for(int i = 0; i<5; i++) {
      System.out.println(i);
      latch.countDown(); // decrement count
    }
  }
}





CountDownLatch: countDown()

 
import java.util.concurrent.CountDownLatch;
   
public class Main {
  public static void main(String args[]) {
    CountDownLatch cdl = new CountDownLatch(5);
    new MyThread(cdl);
   
    try {
      cdl.await();
    } catch (InterruptedException exc) {
      System.out.println(exc);
    }
    System.out.println("Done");
  }
}
   
class MyThread implements Runnable {
  CountDownLatch latch;
   
  MyThread(CountDownLatch c) {
    latch = c;
    new Thread(this).start();
  }
   
  public void run() {
    for(int i = 0; i<5; i++) {
      System.out.println(i);
      latch.countDown(); // decrement count
    }
  }
}