CountDownLatch usage examples

CountDownLatch is a countdown coordinator and under contract.

Usage is very simple, especially similar Thread.join () method, but more flexible than join.

code show as below:

. 1  Package com.moon.forum.controller;
 2  
. 3  Import java.util.concurrent.CountDownLatch;
 . 4  Import java.util.concurrent.TimeUnit;
 . 5  
. 6  public  class the Test {
 . 7      public  static  void main (String [] args) {
 . 8          the try {
 . 9              // countdown initial value. 5 
10              Final a CountDownLatch COUNT = new new a CountDownLatch (. 5 );
 . 11              for ( int I = 0; I <. 5; I ++ ) {
 12 is                  new new the Thread () {
 13 is                     public  void RUN () {
 14                          the try {
 15                              the Thread.sleep (6000 );
 16                          } the catch (Exception E1) {
 . 17                              System.out.println ( "wrong" );
 18 is                          }
 . 19                          System.out.println ( "I thread "+ Thread.currentThread () getName () +." finished " );
 20 is  
21 is                          // decrements a 
22 is                          count.countDown ();
 23 is                      }
 24                  } .start ();
 25             }
 26 is              System.out.println ( "Start Wait" );
 27  
28              // main thread wait 
29              Boolean timeout count.await = (. 5 , TimeUnit.SECONDS);
 30              System.out.println ( "over" + timeout);
 31 is          } the catch (Exception E) {
 32              System.out.println ( "wrong" );
 33          }
 34      }
 35 }

The above code is super easy to understand it. That is the main thread to open five sub-thread. Then each child thread countDown invoked method, and when the countdown to minus 1, when the countdown timer is zero, the main thread is then performed down.

But if there is such a child thread has been blocked, is likely to cause the main thread there is no way to perform it, so usually await (5, TimeUnit.SECONDS), he said that I could only how long, date not wait! Domineering not?

But this will have an implicit fact, even more than the maximum wait time, regardless of the child thread the main thread has not been performed, he continued to perform, but it will continue the sub-thread execution. This is the case when the main thread and the child thread concurrency will appear.

In this business so we used the time, because if the child thread when a timeout and make amends in the main thread of logic, we should note: Because the sub-thread sooner or later executed.

Guess you like

Origin www.cnblogs.com/diexian/p/12652729.html