博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
java多线程对CountDownLatch的使用实例
阅读量:5730 次
发布时间:2019-06-18

本文共 6662 字,大约阅读时间需要 22 分钟。

hot3.png

介绍

CountDownLatch是一个同步辅助类,它允许一个或多个线程一直等待直到其他线程执行完毕才开始执行。

用给定的计数初始化CountDownLatch,其含义是要被等待执行完的线程个数。

每次调用CountDown(),计数减1

主程序执行到await()函数会阻塞等待线程的执行,直到计数为0

实现原理

计数器通过使用锁(共享锁、排它锁)实现

实例1

场景:模拟10人赛跑。10人跑完后才喊"Game Over."

package com.jihite;import java.util.concurrent.CountDownLatch;import java.util.concurrent.ExecutorService;import java.util.concurrent.Executors;public class CountDownLatchTest {    private static final int RUNNER_COUNT = 10;    public static void main(String[] args) throws InterruptedException {        final CountDownLatch begin = new CountDownLatch(1);        final CountDownLatch end = new CountDownLatch(RUNNER_COUNT);        final ExecutorService exec = Executors.newFixedThreadPool(10);        for (int i = 0; i < RUNNER_COUNT; i++) {            final int NO = i + 1;            Runnable run = new Runnable() {                @Override                public void run() {                    try {                        begin.await();                        Thread.sleep((long)(Math.random() * 10000));                        System.out.println("No." + NO + " arrived");                    } catch (InterruptedException e) {                        e.printStackTrace();                    } finally {                        end.countDown();                    }                }            };            exec.submit(run);        }        System.out.println("Game Start ...");        begin.countDown();        end.await();//        end.await(30, TimeUnit.SECONDS);        System.out.println("Game Over.");        exec.shutdown();    }}

分析:代码中定义了2个计数器,个数分别为1和10。

如果不执行begin.countDown(),进程会一致阻塞在begin.await()

主进程执行到end.awit()阻塞等待end计数器清0,进程中每执行一次CountDown()减1,所有执行完后主进程继续往下执行

输出

Game Start ...No.6 arrivedNo.4 arrivedNo.10 arrivedNo.3 arrivedNo.9 arrivedNo.5 arrivedNo.8 arrivedNo.7 arrivedNo.1 arrivedNo.2 arrivedGame Over.

注:countDown()一定要执行到(考虑异常及线程与开始计数设置不一致),否则会一直卡在await()(可以设置时间,超过一定时间就不等了)

实例2(和join的相似处)

场景:流水线上有3个worker: worker1、worker2、worker3,只有当worker1和worker2执行完时才可以执行worker3

WorkerCount.java

package com.jihite;import java.util.concurrent.CountDownLatch;public class WorkerCount extends Thread {    private String name;    private long time;    private CountDownLatch countDownLatch;    public WorkerCount(String name, long time, CountDownLatch countDownLatch) {        this.name = name;        this.time = time;        this.countDownLatch = countDownLatch;    }    @Override    public void run() {        try {            System.out.println(name + "开始工作");            Thread.sleep(time);            System.out.println(name + "工作完成, 耗时:"+ time);            countDownLatch.countDown();            System.out.println("countDownLatch.getCount():" + countDownLatch.getCount());        } catch (InterruptedException e) {            e.printStackTrace();        }    }}

CountDownLatch实现:

@Test    public void CountDownLatchTest() throws InterruptedException {        int COUNT = 2;        final CountDownLatch countDownLatch = new CountDownLatch(COUNT);        WorkerCount worker0 = new WorkerCount("lilei-0", (long)(Math.random() * 10000), countDownLatch);        WorkerCount worker1 = new WorkerCount("lilei-1", (long)(Math.random() * 10000), countDownLatch);        worker0.start();        worker1.start();        countDownLatch.await();        System.out.println("准备工作就绪");        WorkerCount worker2 = new WorkerCount("lilei-2", (long)(Math.random() * 10000), countDownLatch);        worker2.start();        Thread.sleep(10000);    }

输出:

lilei-0开始工作lilei-1开始工作lilei-1工作完成, 耗时:4039countDownLatch.getCount():1lilei-0工作完成, 耗时:9933countDownLatch.getCount():0准备工作就绪lilei-2开始工作lilei-2工作完成, 耗时:6402countDownLatch.getCount():0

该场景join也可以完成

Worker.java

package com.jihite;public class Worker extends Thread{    private String name;    private long time;    public Worker(String name, long time) {        this.name = name;        this.time = time;    }    @Override    public void run() {        try {            System.out.println(name + "开始工作");            Thread.sleep(time);            System.out.println(name + "工作完成, 耗时:"+ time);        } catch (InterruptedException e) {            e.printStackTrace();        }    }}

join实现

@Test    public void JoinTest() throws InterruptedException {        Worker worker0 = new Worker("lilei-0", (long)(Math.random() * 10000));        Worker worker1 = new Worker("lilei-1", (long)(Math.random() * 10000));        Worker worker2 = new Worker("lilei-2", (long)(Math.random() * 10000));        worker0.start();        worker1.start();        worker0.join();        worker1.join();        System.out.println("准备工作就绪");        worker2.start();        Thread.sleep(10000);    }

输出

lilei-0开始工作lilei-1开始工作lilei-1工作完成, 耗时:4483lilei-0工作完成, 耗时:6301准备工作就绪lilei-2开始工作lilei-2工作完成, 耗时:6126

既然这样,那CountDownLatch和join的区别在哪?通过下面的场景三就可以看出

实例3(和join的不同处)

场景:流水线上有3个worker: worker1、worker2、worker3,只有当worker1和worker2两者的阶段一都执行完后才可以执行worker3

WorkerCount2.java

package com.jihite;import java.util.concurrent.CountDownLatch;public class WorkerCount2 extends Thread {    private String name;    private long time;    private CountDownLatch countDownLatch;    public WorkerCount2(String name, long time, CountDownLatch countDownLatch) {        this.name = name;        this.time = time;        this.countDownLatch = countDownLatch;    }    @Override    public void run() {        try {            System.out.println(name + "开始阶段1工作");            Thread.sleep(time);            System.out.println(name + "阶段1完成, 耗时:"+ time);            countDownLatch.countDown();            System.out.println(name + "开始阶段2工作");            Thread.sleep(time);            System.out.println(name + "阶段2完成, 耗时:"+ time);        } catch (InterruptedException e) {            e.printStackTrace();        }    }}

此时用join无法实现,只能用CountDownLatch

@Test    public void CountDownLatchTest2() throws InterruptedException {        int COUNT = 2;        final CountDownLatch countDownLatch = new CountDownLatch(COUNT);        WorkerCount2 worker0 = new WorkerCount2("lilei-0", (long)(Math.random() * 10000), countDownLatch);        WorkerCount2 worker1 = new WorkerCount2("lilei-1", (long)(Math.random() * 10000), countDownLatch);        worker0.start();        worker1.start();        countDownLatch.await();        System.out.println("准备工作就绪");        WorkerCount2 worker2 = new WorkerCount2("lilei-2", (long)(Math.random() * 10000), countDownLatch);        worker2.start();        Thread.sleep(10000);    }

输出

lilei-0开始阶段1工作lilei-1开始阶段1工作lilei-0阶段1完成, 耗时:3938lilei-0开始阶段2工作lilei-1阶段1完成, 耗时:6259lilei-1开始阶段2工作准备工作就绪lilei-2开始阶段1工作lilei-0阶段2完成, 耗时:3938lilei-1阶段2完成, 耗时:6259lilei-2阶段1完成, 耗时:7775lilei-2开始阶段2工作

转载于:https://my.oschina.net/u/3721254/blog/1813393

你可能感兴趣的文章
愚公移山第一章伪代码
查看>>
常见的位运算技巧总结(膜wys)
查看>>
python魔法函数(二)之__getitem__、__len__、__iter__
查看>>
EL表达式无法显示Model中的数据
查看>>
Linux应用小技巧
查看>>
考题纠错2
查看>>
ps6-工具的基础使用
查看>>
关于CefSharp.WinForms的学习
查看>>
灵活运用 SQL SERVER FOR XML PATH
查看>>
es 加磁盘扩容
查看>>
linux 参数内核
查看>>
使用Azcopy在Azure上进行HBase的冷热备份还原
查看>>
计组_定点数一位乘_布斯公式
查看>>
linux下使用过的命令总结(未整理完)
查看>>
ES6的一些文章
查看>>
LeetCode 198, 213 House Robber
查看>>
New Year Permutation(Floyd+并查集)
查看>>
Qt编写输入法V2018超级终结版
查看>>
<context:component-scan>详解
查看>>
DS博客作业07--查找
查看>>