欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

java线程并发countdownlatch类使用示例

程序员文章站 2024-02-22 13:55:52
复制代码 代码如下:package com.yao; import java.util.concurrent.countdownlatch;import java.uti...

复制代码 代码如下:

package com.yao;

import java.util.concurrent.countdownlatch;
import java.util.concurrent.executorservice;
import java.util.concurrent.executors;

/**
 * countdownlatch是个计数器,它有一个初始数,
 * 等待这个计数器的线程必须等到计数器倒数到零时才可继续。
 */
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();
 }
}