CountDownLatch實現計算線程阻塞
package com.thunisoft.countdownlatchExecutor;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.Executor;
import java.util.concurrent.Executors;
public class CountDownLatchTest2 {
public static void main(String[] args) {
//初始化的countDownLatch值X一定和執行的線程數目(y)保持一致,會出現三種情況
//1.x>y導致countdown()方法的返回值不能--為0,導致await線程一致阻塞。程序無法結束
//2.x<y導致對這個線程集合沒有鎖住,導致await提前執行結束,導致,最後的結果信息不能保證什麼時候返回。
CountDownLatch latch = new CountDownLatch(20);
Executor executor = Executors.newFixedThreadPool(2);
List<threads> list = new ArrayList<>();
for (int i = 0; i < 9; i++) {
threads thread = new threads(i, latch);
executor.execute(thread);
list.add(thread);
}
try {
//線程阻塞,如果沒有把 CountDownLatch對象添加到監控的線程中,直接使用出現阻塞,不能執行下面sysout的代碼。
latch.await();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
//此處可以添加任務對上麵線程執行結束的結果處理的方法代替sysout做出處理。
System.out.println("執行結束了");
}
}
class threads implements Runnable {
int x;
CountDownLatch latch;
public threads(int x, CountDownLatch latch) {
this.x = x;
this.latch = latch;
}
@Override
public void run() {
latch.countDown();
System.out.println(Thread.currentThread().getId() + "執行" + x);
}
}
推薦閱讀:
※線程、進程、超線程
※關於如何構建一個線程安全的數組引發的思考
TAG:多線程 |