Example of CountDownLatch and countdownlatch
CountDownLatch is a synchronization helper class, which is like a countDown counter. when an object is created, the initial value is set through the constructor. The await () method of the CountDownLatch object is called and the countDown () method is called () the counter is reduced by 1. When the Count reaches 0, all the waiting persons or individual waiting persons start to execute.
Simple Example
Import java. util. concurrent. countDownLatch;/*** starting point: Wait For All threads to finish running * @ author yinchuan. chen **/public class CountDownLatchTest {public static void main (String [] args) throws InterruptedException {CountDownLatch cdl = new CountDownLatch (4); for (int I = 0; I <4; I ++) {final int count = I; Thread t = new Thread (new Runnable () {public void run () {System. out. println (count); cdl. countDown () ;}}); t. start ();} cdl. await (); System. out. println ("printed only when all on-site executions are completed ");}}
Note:CountDown should be called in finally
Import java. util. concurrent. CountDownLatch; import java. util. concurrent. ExecutorService; import java. util. concurrent. Executors;
Public class CountDownLatchDemo {private static final int PLAYER_AMOUNT = 5; public CountDownLatchDemo () {}/ *** @ param args */public static void main (String [] args) {// CountDownLatch end = new CountDownLatch (PLAYER_AMOUNT); Player [] plays = new Player [PLAYER_AMOUNT]; for (int I = 0; I <PLAYER_AMOUNT; I ++) plays [I] = new Player (I + 1, end); // you can specify a thread pool with a size of 5 ExecutorService exe = Exec. Utors. newFixedThreadPool (PLAYER_AMOUNT); for (Player p: plays) exe.exe cute (p); // allocates the thread System. out. println ("Race begins! "); Try {end. await (); // wait until the end state changes to 0, that is, the end of the game} catch (InterruptedException e) {e. printStackTrace ();} finally {System. out. println ("Race ends! ");} Exe. shutdown () ;}} class Player implements Runnable {private int id; private CountDownLatch end; public Player (int I, CountDownLatch end) {super (); this. id = I; this. end = end ;}@ Override public void run () {try {Thread. sleep (long) (Math. random () * 100); // random allocation time, that is, the athlete's completion time System. out. println ("Play" + id + "arrived. ");} catch (InterruptedException e) {e. printStackTrace ();} finally {end. countDown (); // reduce the end state by 1 and finally to 0 }}}
Reference http://www.cnblogs.com/yezhenhan/archive/2012/01/07/2315652.html