Preliminary study of CountDownLatch

The Chinese translation of CountDownLatch is "lock", and the CountDownLatch class was added in JDK1.5. Provide beneficial help for programmers to carry out concurrent programming.

 

First, let's take a look at the introduction to the CountDownLatch class in the JDK documentation:

A synchronization aid that allows one or more threads to wait until a set of operations being performed in other threads completes.
 The general meaning is that CountDownLatch is a synchronization aid that allows one or more threads to wait until other threads perform operations to complete.

  Its function can replace the join() method in most cases, and is even more flexible than the join() method in practical application.

  Operation process: Create an instance with the CountDownLatch class and specify the number of completion points to wait for. The await() method blocks the current thread until the counter decreases to zero. Each time the thread executes and calls the countDown() method, the counter is decremented by 1, and the waiting thread continues to run until the counter is decremented to 0.

  • Constructor in the CountDownLatch class:
    /**
     * Constructs a {@code CountDownLatch} initialized with the given count.
     *
     * @param count the number of times {@link #countDown} must be invoked
     *        before threads can pass through {@link #await}
     * @throws IllegalArgumentException if { @code count} is negative 
   * The constructor is initialized with the given count as an argument, throws an illegal argument exception if the argument is negative.
   *
*/ public CountDownLatch( int count) { if (count < 0) throw new IllegalArgumentException("count < 0" ); this .sync = new Sync(count); }

 

  • Methods in the CountDownLatch class:

  1. await() method

    /**
     * Causes the current thread to wait until the latch has counted down to
     * zero, unless the thread is {@linkplain Thread#interrupt interrupted}.
     * Causes the current thread to wait until the latched counter is 0, unless the thread is interrupted by an interrupt exception.
     */ 
    public  void await() throws InterruptedException {
        sync.acquireSharedInterruptibly(1);
    }

 

  2. await(long timeout, TimeUnit unit) 方法

    /**
     * Causes the current thread to wait until the latch has counted down to
     * zero, unless the thread is {@linkplain Thread#interrupt interrupted},
     * or the specified waiting time elapses. 
   * Causes the current thread to wait until the lockout counter is 0, unless the thread encounters a thread interrupt abort, or the specified waiting time is exceeded. * @param timeout the maximum time to wait * @param unit the time unit of the { @code timeout} argument specifies the time unit of the maximum wait time * @return { @code true} if the count reached zero and { @code false} * if the waiting time elapsed before the count reached zero * @throws InterruptedException if the current thread is interrupted * while waiting */ public boolean await(long timeout, TimeUnit unit) throws InterruptedException { return sync.tryAcquireSharedNanos(1, unit.toNanos(timeout)); }

 

  3. countDown() method

    /**
     * Decrements the count of the latch, releasing all waiting threads if
     * the count reaches zero.
     * Reduce the count of locks, and release all waiting threads if the count reaches 0
     * <p>If the current count is greater than zero then it is decremented.
     * If the new count is zero then all waiting threads are re-enabled for
     * thread scheduling purposes.
     *
     * <p>If the current count equals zero then nothing happens.
     */
    public void countDown() {
        sync.releaseShared(1);
    }

 

  4. getCount() method

    /**
     * Returns the current count.
     * returns the current counter value
     * <p>This method is typically used for debugging and testing purposes.
     *
     * @return the current count
     */
    public long getCount() {
        return sync.getCount();
    }

 

application:

  There is such a question: using 4 threads to execute concurrently from 1 to 100, each thread can only add 25 numbers, the main thread needs to wait for the completion of the sub-thread before it can end.

  Idea: You can use the join() method or the CountDownLatch object to suspend the main thread.

  Code:

import java.util.concurrent.CountDownLatch;

public  class Compute {
     public  static  int sum = 0; // Store the number from 1 to 100 
    public  static CountDownLatch count = new CountDownLatch(4); // Lock, set the counter to 4

    static  class ComputeThread extends Thread { // Internal class 
        int start, end; // Start and end

        public ComputeThread(int start, int end) {
            this.start = start;
            this.end = end;
        }

        @Override
        public  void run() { // Each thread accumulates 
            for ( int i = start; i <= end; i++ ) {
                sum += i;
            }
            System.out.println(currentThread().getName() + ":" + sum);
            count.countDown();
        }
    }

    public  static  void main(String[] args) throws InterruptedException {
         // Create 4 threads 
        ComputeThread c1 = new Compute.ComputeThread(1, 25 );
        ComputeThread c2 = new Compute.ComputeThread(26, 50);
        ComputeThread c3 = new Compute.ComputeThread(51, 75);
        ComputeThread c4 = new Compute.ComputeThread(76, 100 );
         // Start 4 threads 
        c1.start();
        c2.start();
        c3.start();
        c4.start();
        // Stop the calling thread and wait for the counter to be 0 
        count.await();
        System.out.println(sum);
    }
}
 

Guess you like

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