java线程并发countdownlatch类使用示例
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();
}
}