1. 程式人生 > >多執行緒學習--------CountDownLatch

多執行緒學習--------CountDownLatch

1.概述

猶如倒計時計數器,呼叫CountDownLatch物件的countDown方法就將計數器減1,當計數到達0時,則所有等待者開始執行。

2.程式碼示例

public static void main(String[] args) {
		
		ExecutorService executorService = Executors.newCachedThreadPool();
		CountDownLatch orderLatch = new CountDownLatch(1);
		CountDownLatch answerLatch = new CountDownLatch(3);
		for(int i = 0;i < 3;i++){
			Runnable runnable = new Runnable() {
				@Override
				public void run() {
					try {
						System.out.println("執行緒"+Thread.currentThread().getName()+"正在等待接收命令");
						//等待命令
						orderLatch.await();
						//接收命令(orderLatch的數量減到0)
						System.out.println("執行緒"+Thread.currentThread().getName()+"已經接收命令");
						//執行
						Thread.sleep((long)Math.random()*10000);
						//執行完畢
						System.out.println("執行緒"+Thread.currentThread().getName()+"迴應處理結果");
						//執行完某個執行緒,使得answerCountDownLatch減1
						answerLatch.countDown();
					} catch (InterruptedException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
					
				}
			};
			executorService.execute(runnable);
		}
		try {
			Thread.sleep((long)Math.random()*10000);
			System.out.println("執行緒"+Thread.currentThread().getName()+"即將釋出命令");
			//釋出命令
			orderLatch.countDown();
			System.out.println("執行緒"+Thread.currentThread().getName()+"已經發布命令,正在等待結果");
			//等待所有的answer執行完
			answerLatch.await();
			//所有answer執行完畢,裁判拿到所有人的結果
			System.out.println("執行緒"+Thread.currentThread().getName()+"已經獲取到所有結果");
		} catch (InterruptedException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		executorService.shutdown();
		
		
	}

執行結果: