Java多线程之 使用CountDownLatch来同步多个线程实现一个任务

本文介绍了在多线程开发中如何使用Java的CountDownLatch类来实现主线程等待其他辅助线程完成任务后再继续执行的场景。CountDownLatch初始化时设定资源数,每个线程完成任务后调用countDown()方法,当资源数减为0时,主线程被唤醒执行后续任务。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

               

在多线程开发中,经常会遇到这样的问题,比如,一个线程需要其他的一些辅助线程完成指定的一些任务后才能开

启。 类似于一个主线程正在运行,他需要其他分支线程完成一些任务后才能激活他来启动剩下的任务,这里就可以使用

Java自带的CountDownLatch这个类来帮我们实现这样的效果。   这个类初始化的时候会指定一个数字,这就是需要等

待的资源的数量,每一个资源到位的时候,就调用他的countDown函数,这样就会将资源减一,知道这个资源数字变成

0的时候 ,就会叫醒主线程,来完成剩下的功能,下面我们就使用一个例子来说明这样的情况。


package com.bird.concursey.charpet4;import java.util.concurrent.CountDownLatch;public class Videoconference implements Runnable {  private CountDownLatch controller;  /**  * Implement the constructor of the class that initializes the CountDownLatchattribute. The Videoconference class will wait for the arrival of the number ofparticipants received as a parameter.  * @param number  */ public Videoconference(int number) {  controller = new CountDownLatch(number); }  public void arrive(String name) {  System.out.printf("%s has arrived.",name);  controller.countDown();  System.out.printf("VideoConference: Waiting for %d participants.\n",controller.getCount()); }  @Override public void run() {  System.out.printf("VideoConference: Initialization: %d participants.\n",controller.getCount());  try {   controller.await();   System.out.printf("VideoConference: All the participants have come\n");   System.out.printf("VideoConference: Let's start...\n");  } catch (InterruptedException e) {   e.printStackTrace();  } }}



package com.bird.concursey.charpet4;import java.util.concurrent.TimeUnit;public class Participant implements Runnable {  private Videoconference videoConference;  private String name;  public Participant(Videoconference videoConference, String name) {  this.videoConference = videoConference;  this.name = name; } @Override public void run() {  long duration=(long)(Math.random()*10);  try {   TimeUnit.SECONDS.sleep(duration);  } catch (InterruptedException e) {   e.printStackTrace();  }  videoConference.arrive(name); }  public static void main(String[] args) {  //Create a Videoconference object named conference that waits for 10 participants.  Videoconference videoCOnference = new Videoconference(10);  Thread threadConference = new Thread(videoCOnference);  threadConference.start();    for(int i = 0; i < 10; i++) {   Participant participant = new Participant(videoCOnference, "participant" + i);   Thread t = new Thread(participant);   t.start();  } }}


           

再分享一下我老师大神的人工智能教程吧。零基础!通俗易懂!风趣幽默!还带黄段子!希望你也加入到我们人工智能的队伍中来!https://blog.youkuaiyun.com/jiangjunshow

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值