java線程並發countdownlatch類應用示例。本站提示廣大學習愛好者:(java線程並發countdownlatch類應用示例)文章只能為提供參考,不一定能成為您想要的結果。以下是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();
}
}