栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

java线程并发countdownlatch类使用示例

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

java线程并发countdownlatch类使用示例

复制代码 代码如下:
package com.yao;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;


public class CountDownLatchTest {

 
 public static class ComponentThread implements Runnable {
  // 计数器
  CountDownLatch latch;
  // 组件ID
  int ID;

  // 构造方法
  public ComponentThread(CountDownLatch latch, int ID) {
   this.latch = latch;
   this.ID = ID;
  }

  public void run() {
   // 初始化组件
   System.out.println("Initializing component " + ID);
   try {
    Thread.sleep(500 * ID);
   } catch (InterruptedException e) {
   }
   System.out.println("Component " + ID + " initialized!");
   //将计数器减一
   latch.countDown();
  }
 }

 
 public static void startServer() throws Exception {
  System.out.println("Server is starting.");
  //初始化一个初始值为3的CountDownLatch
  CountDownLatch latch = new CountDownLatch(3);
  //起3个线程分别去启动3个组件
  ExecutorService service = Executors.newCachedThreadPool();
  service.submit(new ComponentThread(latch, 1));
  service.submit(new ComponentThread(latch, 2));
  service.submit(new ComponentThread(latch, 3));
  service.shutdown();

  //等待3个组件的初始化工作都完成
  latch.await();

  //当所需的三个组件都完成时,Server就可继续了
  System.out.println("Server is up!");
 }

 public static void main(String[] args) throws Exception {
  CountDownLatchTest.startServer();
 }
}

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/152630.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号