CountDownLatch

CountDownLatch类

1. CountDownLatch类介绍

  • java.util.concurrent.CountDownLatch

  • 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.
      (在count减为0之前,所有线程等待)
  • 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.

  • (CountDownLatch的一个好处在于不需要线程去调用countDown()方法就可以实现count值减为0之前所有线程等待)

2. CountDownLatch类使用

import java.util.concurrent.CountDownLatch;

/*
 *  startSignal是一个启动信号,在 driver 为继续执行 worker 做好准备之前,它会阻止所有的 worker 继续执行。
    doneSignal是一个完成信号,它允许 driver 在完成所有 worker 之前一直等待。
 * */

public class TestCountDownLatch {
    public static void main(String[] args) throws InterruptedException{
        CountDownLatch startSignal = new CountDownLatch(1);
        CountDownLatch doneSignal = new CountDownLatch(10);
        
        for(int i = 0;i < 10;++i) {
            new Thread(new Worker(startSignal,doneSignal)).start(); //10个线程启动
        }
        
        doSomethingElse();      // don't let run yet——此时count仍旧为1,不可以执行其他线程
        startSignal.countDown();  // let all threads proceed——count减为0,10个线程启动
        doSomethingElse();          
        doneSignal.await();     // wait for all to finish——10个线程执行结束前,不可以再向下执行
        
        System.out.println("hahahaha");
    }

    private static void doSomethingElse() {
        // TODO Auto-generated method stub
        System.out.println("doing something else");     
    }
}

class Worker implements Runnable{
    private final CountDownLatch startSignal;
    private final CountDownLatch doneSignal;
    
    Worker(CountDownLatch startSignal,CountDownLatch doneSignal){
        this.startSignal = startSignal;
        this.doneSignal = doneSignal;
    }
    
    @Override
    public void run() {
        try {
            startSignal.await();           //线程等待,直到startSignal中参数为0
            doWork();
            doneSignal.countDown();         //每个线程执行一次run方法,则countDown()执行一次,最后10个线程执行完毕以后
        }catch(InterruptedException e) {
            e.printStackTrace();
        }       
    }

    private void doWork() {
        Count.add();        
    }   
}

class Count{
    public static int num = 0;
    
    public static void add() {        //完成计数器工作
        System.out.println(Thread.currentThread().getName() + " : " + num++);
    }
}

你可能感兴趣的:(CountDownLatch)