zoukankan      html  css  js  c++  java
  • Java深入学习08:CountDownLatch应用

    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实现"在前面的任务全部完成后才可以执行"

  • 相关阅读:
    第02周学习提升建议:【python安装、变量、输入输出、流程、循环】--【第五篇】流程、循环
    向gitlab上传本地项目
    [jenkins+gitlab+postman] 持续集成
    linux 上安装newman
    【python】读取cfg/ini/txt配置文件
    【CI/CD】docker部署gitlab,并且本地拉取gitlab代码成功
    【CI/CD】docker部署Jenkins
    【TCP知识】03_Linux查看TCP连接状态
    【nginx知识】02_【转载】nginx反向代理时保持长连接
    【TCP/IP知识】02_【转载】TCP 半连接队列和全连接队列
  • 原文地址:https://www.cnblogs.com/wobuchifanqie/p/12512337.html
Copyright © 2011-2022 走看看