国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 編程 > Java > 正文

java線程并發countdownlatch類使用示例

2019-11-26 15:46:16
字體:
來源:轉載
供稿:網友

復制代碼 代碼如下:

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();
 }
}

發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 孟津县| 菏泽市| 华亭县| 仁寿县| 通江县| 柳州市| 焉耆| 河北省| 沙雅县| 鄂伦春自治旗| 冀州市| 宣城市| 武穴市| 浪卡子县| 秀山| 新邵县| 普安县| 济源市| 麻栗坡县| 锡林郭勒盟| 江陵县| 大港区| 阳东县| 南涧| 滕州市| 化隆| 策勒县| 沙河市| 馆陶县| 新密市| 芜湖市| 曲沃县| 农安县| 海盐县| 怀仁县| 万州区| 墨玉县| 那曲县| 通海县| 琼结县| 永胜县|