Java深入学习08:CountDownLatch应用

一、CountDownLatch是什么

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

  CountDownLatch是一个同步助手,它允许一个或多个线程在在其他线程中执行的一组操作完成前,一直处于等待状态。

二、案例

 

public class CountDownLatchTest {
    public static void main(String[] args) {
        CountDownLatch latch = new CountDownLatch(100);
        CountDownLatchThread th = new CountDownLatchThread(latch);
        long start = System.currentTimeMillis();
        for(int i = 0; i< 100; i++){
            new Thread(th).start();
        }
        try {
            latch.await();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        long end = System.currentTimeMillis();
        System.out.println("一共花费:" + (end - start) + " 毫秒");

    }
}
class CountDownLatchThread implements Runnable{
    private CountDownLatch latch ;
    public CountDownLatchThread(CountDownLatch latch){
        this.latch = latch;
    }
    @Override
    public void run() {
        try {
            System.out.println(Thread.currentThread().getName()+"完成任务");
        } finally {
            //计数减1
            latch.countDown();
        }
    }
}

 

 日志输出

Thread-0完成任务
Thread-5完成任务
Thread-4完成任务
Thread-3完成任务
Thread-2完成任务
Thread-1完成任务
.......
Thread-97完成任务
Thread-99完成任务
一共花费:11 毫秒

Process finished with exit code 0

 

三、CountDownLatch主要方法   

   //计数
   //Decrements the count of the latch, releasing all waiting threads if  the count reaches zero.
    public void countDown() {
        sync.releaseShared(1);
    }
  
    //等待
   //the current thread to wait until the latch has counted down to zero
    public void await() throws InterruptedException {
        sync.acquireSharedInterruptibly(1);
    }

 

 

 

四、应用场景

  当一个主任务中,有多个子任务可以同时进行(多个线程),最有有一个或多个子任务,需要在前面的任务全部完成后才可以执行,那么就可以用CountDownLatch实现"在前面的任务全部完成后才可以执行"

posted on 2020-03-17 17:56  我不吃番茄  阅读(111)  评论(0编辑  收藏  举报