Java多线程之CountDownLatch

2021-03-03 07:30

阅读:426

标签:rpo   doc   return   before   param   serve   released   orm   property   

 

在java.util.concurrent包中,有一个CountDownLatch的多线程同步器。参考javadoc的说明如下:

“A synchronization aid that allows one or more threads to wait until a set of operations being performed in other threads completes.”

即它是当前线程用于等待若干子线程完成和结束的同步工具,典型使用场景是。


A CountDownLatch is initialized with a given count. The await methods block until the current count reaches zero due to invocations of the countDown method, after which all waiting threads are released and any subsequent invocations of await return immediately. This is a one-shot phenomenon -- the count cannot be reset. If you need a version that resets the count, consider using a CyclicBarrier.
A CountDownLatch is a versatile synchronization tool and can be used for a number of purposes. A CountDownLatch initialized with a count of one serves as a simple on/off latch, or gate: all threads invoking await wait at the gate until it is opened by a thread invoking countDown. A CountDownLatch initialized to N can be used to make one thread wait until N threads have completed some action, or some action has been completed N times.
A useful property of a CountDownLatch is that it doesn‘t require that threads calling countDown wait for the count to reach zero before proceeding, it simply prevents any thread from proceeding past an await until all threads could pass.
Sample usage: Here is a pair of classes in which a group of worker threads use two countdown latches:
The first is a start signal that prevents any worker from proceeding until the driver is ready for them to proceed;
The second is a completion signal that allows the driver to wait until all workers have completed.
  
 class Driver { // ...
   void main() throws InterruptedException {
     CountDownLatch startSignal = new CountDownLatch(1);
     CountDownLatch doneSignal = new CountDownLatch(N);

     for (int i = 0; i // create and start threads
       new Thread(new Worker(startSignal, doneSignal)).start();

     doSomethingElse();            // don‘t let run yet
     startSignal.countDown();      // let all threads proceed
     doSomethingElse();
     doneSignal.await();           // wait for all to finish
   }
 }

 class Worker implements Runnable {
   private final CountDownLatch startSignal;
   private final CountDownLatch doneSignal;
   Worker(CountDownLatch startSignal, CountDownLatch doneSignal) {
     this.startSignal = startSignal;
     this.doneSignal = doneSignal;
   }
   public void run() {
     try {
       startSignal.await();
       doWork();
       doneSignal.countDown();
     } catch (InterruptedException ex) {} // return;
   }

   void doWork() { ... }
 }
Another typical usage would be to divide a problem into N parts, describe each part with a Runnable that executes that portion and counts down on the latch, and queue all the Runnables to an Executor. When all sub-parts are complete, the coordinating thread will be able to pass through await. (When threads must repeatedly count down in this way, instead use a CyclicBarrier.)
  
 class Driver2 { // ...
   void main() throws InterruptedException {
     CountDownLatch doneSignal = new CountDownLatch(N);
     Executor e = ...

     for (int i = 0; i // create and start threads
       e.execute(new WorkerRunnable(doneSignal, i));

     doneSignal.await();           // wait for all to finish
   }
 }

 class WorkerRunnable implements Runnable {
   private final CountDownLatch doneSignal;
   private final int i;
   WorkerRunnable(CountDownLatch doneSignal, int i) {
     this.doneSignal = doneSignal;
     this.i = i;
   }
   public void run() {
     try {
       doWork(i);
       doneSignal.countDown();
     } catch (InterruptedException ex) {} // return;
   }

   void doWork() { ... }
 }

 

 

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.atomic.AtomicInteger;

public class NumberPrinterTest {
    private static final int            max         = 10;
    private static final CountDownLatch beginSignal = new CountDownLatch(1);
    private static final CountDownLatch endSignal   = new CountDownLatch(2);
    private static final AtomicInteger  counter     = new AtomicInteger(1);

    /**
     * 两个线程分别打印1-10,10个数字,最后主线程打印一行end
     * @param args
     * @throws InterruptedException
     */
    public static void main(String[] args) throws InterruptedException {

        System.out.println("start");
        ExecutorService fixedThreadPool = Executors.newFixedThreadPool(2);
        fixedThreadPool.submit(new Printer(true, beginSignal, endSignal));
        fixedThreadPool.submit(new Printer(false, beginSignal, endSignal));

        beginSignal.countDown();
        endSignal.await();
        System.out.println("end");

        fixedThreadPool.shutdown();
    }

    private static class Printer implements Runnable {

        private final boolean        evenNumberPrinter;
        private final CountDownLatch begin;
        private final CountDownLatch end;

        public Printer(boolean evenNumberPrinter, CountDownLatch begin, CountDownLatch end) {
            this.evenNumberPrinter = evenNumberPrinter;
            this.begin = begin;
            this.end = end;
        }

        @Override
        public void run() {

            try {
                begin.await();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }

            while (true) {
                synchronized (counter) {
                    int v = counter.get();
                    if (v > max) {
                        end.countDown();
                        break;
                    }

                    if ((evenNumberPrinter && v % 2 == 0) || (!evenNumberPrinter && v % 2 == 1)) {
                        System.out.println(counter.getAndIncrement());
                    }
                }
            }
        }
    }
}

 

Java多线程之CountDownLatch

标签:rpo   doc   return   before   param   serve   released   orm   property   

原文地址:https://www.cnblogs.com/jacksonshi/p/14398540.html


评论


亲,登录后才可以留言!