1. 程式人生 > >juc併發工具類之CountDownLatch閉鎖

juc併發工具類之CountDownLatch閉鎖

import java.util.concurrent.CountDownLatch;

/**
* 閉鎖: 在進行某些運算時, 只有其他所有執行緒的運算全部完成,當前運算才繼續執行(程式流中加了一道柵欄)
* 聯想: 相當於水電站的水壩, 會攔截上游的水, 當積累到一定水位才放水.
* 馬場賽馬,需要所有的馬跑完比賽才能公佈比賽的排名結果
*
*
*/
//計算多執行緒程式執行時間 : 分執行緒執行完的時間 + 主執行緒執行的時間(分執行緒必須全部在結算前執行完)
public class CountDownLatchTest {
public static void main(String[] args) throws InterruptedException {
long start = System.currentTimeMillis();

//1.初始化CountDownLatch計算執行緒的數量 10
CountDownLatch latch = new CountDownLatch(10);
LatchTask latchTask = new LatchTask(latch);

for (int i = 0; i < 10; i++) {
new Thread(latchTask).start();
}

//4.阻塞主線執行緒, 當CountDownLatch計數為0時才會繼續執行
latch.await();

long end = System.currentTimeMillis();
System.out.println("程式消耗時間" + (end - start));
}
}

class LatchTask implements Runnable{

//2.所有執行緒共有一個CountDownLatch計數
private CountDownLatch latch;
LatchTask(CountDownLatch latch){
this.latch = latch;
}

@Override
public void run() {
synchronized (this){
try {
for (int i = 0; i < 1000; i++) {
if(i % 2 == 0){
System.out.println(i);
}
}
} finally {
//3. 一個執行緒執行完後計數減1
latch.countDown();
}
}
}
}