Detailed concurrent usage of CountDownLatch

concept

       CountDownLatch class is a synchronization tool that allows one or more threads to wait until another thread execution after their execution. For example, the application's main thread after thread of hope that the implementation of the framework is responsible for starting the service has been launched in the framework of all the services.

 

CountDownLatch usage

CountDownlacth typical usage 1:

One thread to wait n thread is finished before starting the run. CountDownLatch The counter is initialized to n (new CountDownLatch (n)) , each time a task thread is finished, the counter will be minus 1 (countdownlatch.countDown ()), when the counter value becomes 0, in CountDownLatch  await() thread it will be awakened. A typical scenario is when a service starts, the main thread needs to wait for a number of components loaded before continuing execution.

 

CountDownLatch Typical Usage 2:

Maximum parallelism to achieve multiple threads begin to perform tasks. Note that parallelism, not concurrent, emphasized that multiple threads simultaneously started at a time. Similar to the race, the starting point into multiple threads, waiting for the starting gun, then started running at the same time. Practice is to initialize a shared CountDownLatch (1), its counter is initialized to 1, first coundownlatch.await multiple threads before starting the task (), when the main thread calls countDown (), counter reaches zero, multiple threads simultaneously wake up.

 

CountDownlatch principle

Achieved by a number of the counter, the initial value of the thread counter. Whenever a thread after the completion of its mandate, the value of the corresponding counter is decremented by one. When the counter reaches zero, indicating that all threads have completed the task, and then wait for the thread locking can be restored on a mission.

 

 

Use examples:

 1 public static void main(String[] args) throws InterruptedException {
 2         CountDownLatch latch = new CountDownLatch(10);
 3  
 4         for (int i=0; i<9; i++) {
 5             new Thread(new Runnable() {
 6                 @Override
 7                 public void run() {
 8                     System.out.println(Thread.currentThread().getName() + " 运行");
 9                     try {
10                         Thread.sleep (3000 );
 . 11                      } the catch (InterruptedException E) {
 12 is                          e.printStackTrace ();
 13 is                      } the finally {
 14                          latch.countDown ();
 15                      }
 16                  }
 . 17              .}) Start ();
 18 is          }
 . 19   
20 is          the System .out.println ( "wait for the child thread running end" );
 21          latch.await (10 , TimeUnit.SECONDS);
 22          System.out.println ( "end child thread running.");
23 }

 

2 child threads wait for the main thread begins processing processed, processed after the child thread, the main thread output

class MyRunnable implements Runnable {
 
    private CountDownLatch countDownLatch;
 
    private CountDownLatch await;
 
    public MyRunnable(CountDownLatch countDownLatch, CountDownLatch await) {
        this.countDownLatch = countDownLatch;
        this.await = await;
    }
 
    @Override
    public void run() {
        try {
            countDownLatch.await();
            System.out.println("子线程" +Thread.currentThread().getName()+ "处理自己事情");
            Thread.sleep(1000);
            await.countDown();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
 
    }
}
public  static  void main (String [] args) throws InterruptedException { 
        a CountDownLatch CountDownLatch = new new a CountDownLatch (. 1 ); 
        a CountDownLatch the await = new new a CountDownLatch (. 5 ); 
 
        for ( int I = 0; I <. 5; I ++ ) {
             new new the Thread ( new new MyRunnable (CountDownLatch, the await)) Start ();. 
        } 
 
        System.out.println ( "main thread to handle their own thing" ); 
        Thread.sleep ( 3000 ); 
        countDownLatch.countDown();
        System.out.println ( "main thread ended" ); 
        await.await (); 
        System.out.println ( "child thread processed matter" ); 
    }

 

Usage scenarios in real-time systems
for maximum parallelism: Sometimes we want to start multiple threads to achieve the greatest degree of parallelism. For example, we want to test a singleton class. If we create an initial counter CountDownLatch 1 and all other threads are waiting on the lock, just call once countDown () method can be used for all other waiting threads resume execution.
N threads waiting to complete their tasks before you begin: for example, to ensure that the application starts classes before processing user requests, all N external systems are already up and running.
Deadlock detection: a very convenient usage scenario is that you use N threads to access shared resources, different number of threads in each test phase, and try to deadlock.

 

----------------
Disclaimer: This article is CSDN blogger "spring breeze Shili less than you." Original article, follow the CC 4.0 BY-SA copyright agreement, reproduced, please attach the original source link and this statement.
Original link: https: //blog.csdn.net/qq812908087/article/details/81112188

Guess you like

Origin www.cnblogs.com/yrjns/p/12163745.html