zoukankan      html  css  js  c++  java
  • java CountDownLatch的使用

    CountDownLatch能够使一个线程在等待另外一些线程完成各自工作之后,再继续执行。使用一个计数器进行实现。计数器初始值为线程的数量。当每一个线程完成自己任务后,计数器的值就会减一。当计数器的值为0时,表示所有的线程都已经完成了任务,然后在CountDownLatch上等待的线程就可以恢复执行任务。类似join()的作用,join()也可以实现等待一些线程的完成,再执行后面线程。
    CountDownLatch 例子:

    package com.hts;
    
    import java.util.concurrent.CountDownLatch;
    import java.util.concurrent.ExecutorService;
    import java.util.concurrent.Executors;
    
    public class CountDownLatchTest {
        class Task1 implements Runnable{
            CountDownLatch countDownLatch;
    
            Task1(CountDownLatch countDownLatch){
                this.countDownLatch = countDownLatch;
            }
            @Override
            public void run() {
                System.out.println("任务1执行了");
                countDownLatch.countDown();
            }
        }
        class Task2 implements Runnable{
            CountDownLatch countDownLatch;
    
            Task2(CountDownLatch countDownLatch){
                this.countDownLatch = countDownLatch;
            }
            @Override
            public void run() {
                System.out.println("任务2执行了");
                countDownLatch.countDown();
            }
        }
        class Task3 implements Runnable{
            CountDownLatch countDownLatch;
    
            Task3(CountDownLatch countDownLatch){
                this.countDownLatch = countDownLatch;
            }
            @Override
            public void run() {
                System.out.println("任务3执行了");
                countDownLatch.countDown();
            }
        }
    
        public static void main(String[] args) {
            CountDownLatch countDownLatch = new CountDownLatch(3);
            ExecutorService executorService = Executors.newFixedThreadPool(3);
            System.out.println("任务开始执行");
            executorService.submit(new CountDownLatchTest().new Task1(countDownLatch));
            executorService.submit(new CountDownLatchTest().new Task2(countDownLatch));
            executorService.submit(new CountDownLatchTest().new Task3(countDownLatch));  //位置①
            try {
                countDownLatch.await();
                System.out.println("三个任务执行完");
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
    
        }
    }
    
    

    执行结果:

    如果把位置①的那行代码注释掉,使得计数器CountDownLatch无法减到0,则会一直阻塞着,等待减到0.
    结果如下:

  • 相关阅读:
    IIS7 503错误 Service Unavailable
    android错误系列之导出数据库出错Failed to pull selection
    android学习笔记(入门篇)
    使用cmd命令删除文件夹下所有文件
    vue 动态插入组件
    js获取当前时间
    获取带参值
    以毫秒为单位的时间长度转化为时分秒时间格式的时间长度
    js如何复制一个对象?
    想在已创建的Vue工程里引入vux组件
  • 原文地址:https://www.cnblogs.com/hts-technology/p/9305870.html
Copyright © 2011-2022 走看看