java線程並發countdownlatch類使用樣本_java

來源:互聯網
上載者:User

複製代碼 代碼如下:

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

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.