026 Concurrency helper--CountDownLatch

I. Overview

  Earlier we talked about using Condition to achieve precise control of threads, but in our daily use, we found that our concurrency always has some rules.

  For example, after a certain thread completes its task, the thread starts, and such a scenario always occurs frequently in concurrent scenarios.

  To this end, JUC provides concurrency helper classes to help us simplify the implementation of this thread concurrency scenario.


 

2. CountDownLatch

  Let's first look at the structure of this class:

  Constructor:

public CountDownLatch(int count) 

where the int value represents the number of semaphores to wait for.

public void countDown()

Decrease a semaphore, indicating that the number of waiting threads is decreased by one.

 public  void  await ()

It is the thread blocking until the thread acquires enough semaphores.

  In general, we can compare CountDownLatch to a rocket launcher, the number of signals keeps decreasing, 5, 4, 3, 2, 1. Then the blocked thread starts.


 

3. Example demonstration 

public class CountDownLathchTest {
    
    //
     
    public  static  void main(String[] args) {
         // Create a CountDownLatch, where the parameter indicates that the number of semaphores required is 10 
        CountDownLatch latch = new CountDownLatch( 10 );
        Thread thread = new Thread(new Runnable() {
            @Override
            public  void run() {
                 // The defined main thread blocks 
                try {
                    latch.await();System.out 
                    .println ( " I can finally run.. " );
                } catch (InterruptedException e) {
                    e.printStackTrace ();
                }
            }
        });
        thread.start();
        // Open 10 threads below, each thread releases a semaphore. 
        for ( int x = 0 ; x< 10 ; x++ ) {
            final int temp = x ; 
            new Thread(()-> {
                try {
                    TimeUnit.SECONDS.sleep(temp);
                } catch (InterruptedException e) {
                    e.printStackTrace ();
                }
                // Release a semaphore System.out 
                .println (temp+ " Thread released the semaphore " );
                latch.countDown();
            }) .start();
        }
    }
}

We can see that the main thread we defined needs to wait for the release of 10 semaphores to run.


4. Function

  What can CountDownLatch do? 

  First of all, it can start a thread task, but it needs enough semaphore, that is to say, we can start the running of a thread task by releasing the semaphore.

  Overall, this class is fairly simple, but the effect is obvious. 


 

5. Realization

  Nothing, AQS is the way of implementation. The int in AQS represents the number of this semaphore.

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325897389&siteId=291194637