java多线程对CountDownLatch的使用实例

介绍

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 arrived
No.4 arrived
No.10 arrived
No.3 arrived
No.9 arrived
No.5 arrived
No.8 arrived
No.7 arrived
No.1 arrived
No.2 arrived
Game Over.

实例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工作完成, 耗时:4039
countDownLatch.getCount():1
lilei-0工作完成, 耗时:9933
countDownLatch.getCount():0
准备工作就绪
lilei-2开始工作
lilei-2工作完成, 耗时:6402
countDownLatch.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工作完成, 耗时:4483
lilei-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完成, 耗时:3938
lilei-0开始阶段2工作
lilei-1阶段1完成, 耗时:6259
lilei-1开始阶段2工作
准备工作就绪
lilei-2开始阶段1工作
lilei-0阶段2完成, 耗时:3938
lilei-1阶段2完成, 耗时:6259
lilei-2阶段1完成, 耗时:7775
lilei-2开始阶段2工作

原文地址:https://www.cnblogs.com/kaituorensheng/p/9043494.html

时间: 2024-11-09 00:34:44

java多线程对CountDownLatch的使用实例的相关文章

Java多线程-----理解CountDownLatch

   CountDownLatch简介  CountDownLatch是在java1.5被引入的,跟它一起被引入的并发工具类还有CyclicBarrier.Semaphore.ConcurrentHashMap和BlockingQueue,它们都存 在于java.util.concurrent包下.CountDownLatch是一个同步工具类,它允许一个或多个线程一直等待,直到其他线程的操作执行完后再执行 CountDownLatch工作原理 CountDownLatch.java类中定义的构造

【Java多线程】CountDownLatch同步辅助类

CountDownLatch,一个同步辅助类,在完成一组正在其他线程中执行的操作之前,它允许一个或多个线程一直等待. 主要方法: public CountDownLatch(int count);  //构造方法参数, 指定了计数的次数 public void countDown();        //调用此方法,则计数减一 public void await();        //调用此方法会一直阻塞当前线程,直到计时器的值为0 代码: import java.util.concurren

Java多线程:CountDownLatch、CyclicBarrier 和 Semaphore

场景描述: 多线程设计过程中,经常会遇到需要等待其它线程结束以后再做其他事情的情况,比如多线程下载文件,每个线程都会下载文件的一部分,在所有线程结束以后,需要将各部分再次拼接成一个完整的文件. 有几种方案: 1.在主线程中设置一自定义全局计数标志,在工作线程完成时,计数减1.主线程侦测该标志是否为0,一旦为0,表示所有工作线程已经完成. 2.使用Java标准的类CountDownLatch来完成这项工作,原理是一样的,计数. CountDownLatch 一个同步辅助类,在完成一组正在其他线程中

java多线程很好的一个实例

java中的多线程 在java中要想实现多线程有两种手段一种是继续Thread类另外一种是实现Runable接口. 对于直接继承Thread的类来说代码大致框架是 ? 1 2 3 4 5 6 7 8 9 10 11 12 class 类名extends Thread{ 方法1; 方法2 … public void run(){ // other code… } 属性1 属性2 … } 先看一个简单的例子 ? 1 2 3 4 5 6 7 8 9 1 0 1 1 1 2 1 3 1

Java多线程协作CountDownLatch,主线程等待子线程结束

CountDownLatch,一个同步辅助类,在完成一组正在其他线程中执行的操作之前,它允许一个或多个线程一直等待. 主要方法 public CountDownLatch(int count);构造方法参数指定了计数的次数 public void countDown(); countDown方法,当前线程调用此方法,则计数减一 public void await() awaint方法,调用此方法会一直阻塞当前线程,直到计时器的值为0 ===============================

《Java多线程编程核心技术》推荐

写这篇博客主要是给猿友们推荐一本书<Java多线程编程核心技术>. 之所以要推荐它,主要因为这本书写得十分通俗易懂,以实例贯穿整本书,使得原本抽象的概念,理解起来不再抽象. 只要你有一点点Java基础,你就可以尝试去阅读它,相信定会收获甚大! 博主之前网上找了很久都没完整pdf电子版的,只有不全的试读版,这里博主提供免费.清晰.完整版供各位猿友下载: http://download.csdn.net/detail/u013142781/9452683 刚刚已经提到,<Java多线程编程核

java基础----&gt;java多线程的使用(四)

线程的priority能告诉调度程序其重要性如何,今天我们通过实例来学习一下java多线程中的关于优先级的知识. java多线程的优先级 一.java多线程中关于优先级的实例 package com.linux.huhx.thread1; import java.util.Random; import java.util.concurrent.TimeUnit; public class PriorityThread extends Thread { PriorityThread(String

Java多线程系列——计数器 CountDownLatch

简介: CountDownLatch 是一个非常实用的多线程控制工具类,通常用来控制线程的等待,它可以让某个线程等待直到倒计时结束 CountDownLatch 提供了两个主要的方法,await().countDown(). await:使当前线程阻塞,等待计数器为 0 countDown:计数器减一,计数为零时,释放所有在等待的线程 实例: public class CountDownLatchDemo implements Runnable { static final CountDownL

Java多线程20:多线程下的其他组件之CountDownLatch、Semaphore、Exchanger

前言 在多线程环境下,JDK给开发者提供了许多的组件供用户使用(主要在java.util.concurrent下),使得用户不需要再去关心在具体场景下要如何写出同时兼顾线程安全性与高效率的代码.之前讲过的线程池.BlockingQueue都是在java.util.concurrent下的组件,Timer虽然不在java.util.concurrent下,但也算是.后两篇文章将以例子的形式简单讲解一些多线程下其他组件的使用,不需要多深刻的理解,知道每个组件大致什么作用就行. 本文主要讲解的是Cou