CountDownLatch How to use?

  • CountDownLatch can play a role in the starting gun, JDK 1.5 started offering
  • After CountDownLatch concurrent access, hoping to reach a condition when writing test tools, all threads execute simultaneously
  • It can also be used to achieve CountDownLatch, a thread waiting for other threads to finish, the final unity deal

 

code show as below:

package constxiong.interview;

import java.util.concurrent.CountDownLatch;

/**
 * Test using 100 threads, multi-threaded concurrent access and wait after the completion of treatment
 * @author ConstXiong
 */
public class TestCountDownLatch2 {

    private static CountDownLatch cdl = new CountDownLatch(100);
    
    private static int count = 0;
    
    public static void main(String[] args) {
        testConcurrent();
//        testDoAfterOtherThreadComplete();
    }
    
    /**
     * Testing Concurrent do something ...
     * / 
    Private  static  void testConcurrent () {
         for ( int I = 0 ; I < 100 ; I ++ ) {
             // start threads 
            new new the Thread (() -> {
                 the try {
                     // when the starting gun is not reduced to 0 before the count of the threads in this blockage 
                    . CDL the await ();
                } catch (InterruptedException e) {
                    e.printStackTrace ();
                }
                System.out.println(Thread.currentThread().getName() + ":" + System.currentTimeMillis() + " do something...");
            }).start();
            
            // starting gun count is decremented. 1 
            cdl.countDown ();
        }
    }
    
    // test After completion of the processing thread waits 
    Private  static  void testDoAfterOtherThreadComplete () {
         // Start of threads 100, is incremented to count 
        for ( int I = 0 ; I < 100 ; I ++ ) {
             new new the Thread (() -> {
                COUNT ++ ;
                 // starting gun count is decremented. 1 
                cdl.countDown ();
            }).start();
        }
        
        try {
            CDL. await ();
        } catch (InterruptedException e) {
            e.printStackTrace ();
        }
        System.out.println("main thread print count : " + count);
    }
    
}

 


Description link
 


 

 

Guess you like

Origin www.cnblogs.com/ConstXiong/p/12093229.html