A?CountDownLatch?is initialized with a givencount. Theawait()?methods block until the current count reaches zero due to invocations of the countDown()?method, after which all waiting threads are released and any subsequent invocations ofawait()?return immediately.?
?
A useful property of aCountDownLatch?is that it doesn't require that threads callingcountDown?wait for the count to reach zero before proceeding, it simply prevents any thread from proceeding past anawait()?until all threads could pass.?
countDownLatch jdk里描述? A synchronization aid that allows one or more threads to wait until? a set of operations being performed in other threads completes.? 一個允許等待一個或多個其它線程執行完成的同步助手? 使用場景:? 1.等待一個或多個線程完成再執行其它操作? 2.等待一個線程執行多次再執行其它操作?
countDownLatch實現原理
private final Sync sync;
public CountDownLatch(int count) {if (count < 0) throw new IllegalArgumentException("count < 0");this.sync = new Sync(count);}
初始化時將任務個數傳遞給同步控制器Sync,每次調用countDown方法,開始執行異步任務,Sync釋放一個資源
public void countDown() {sync.releaseShared(1);}調用await,await方法判斷Sycn的狀態,如果Sync狀態顯示未執行完成,則繼續分配資源執行。
當countDown為0時,統一返回異步結果。
代碼示例
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.*;public class MultiJobExecutors {private CountDownLatch countDownLatch;private List<Task> tasks;private static ExecutorService executor = null;public MultiJobExecutors(List<Task> tasks) {countDownLatch = new CountDownLatch(tasks.size());executor = Executors.newFixedThreadPool(tasks.size());this.tasks = tasks;}public void execute() {if (tasks == null|| tasks.isEmpty()) {return;}for (int i=0;i< tasks.size();i++) {executor.submit(new Job(countDownLatch,tasks.get(i)));System.out.println("xx"+i);}try {//等待所有線程結束countDownLatch.await(15, TimeUnit.SECONDS);//執行其他操作System.out.println("it's over");//關閉線程池executor.shutdown();} catch (InterruptedException e) {e.printStackTrace();}}private class Job implements Callable<Object>{private CountDownLatch latch;private Task task;public Job(CountDownLatch latch, Task task) {this.latch = latch;this.task = task;}@Overridepublic Object call() throws Exception {System.out.println(System.currentTimeMillis());//執行線程task.execute();//countDown自減latch.countDown();return null;}}private static class Task{private String str;public Task(String str) {this.str = str;}public void execute(){System.out.println(str);}}public static void main(String[] args) {Task task = new Task("I");Task task1 = new Task("love");Task task2 = new Task("you");Task task3 = new Task(",");Task task4 = new Task("its");Task task5 = new Task("not");Task task6 = new Task("true");List<Task> tasks = new ArrayList<Task>();tasks.add(task);tasks.add(task1);tasks.add(task2);tasks.add(task3);tasks.add(task4);tasks.add(task5);tasks.add(task6);MultiJobExecutors multiJobExecutors = new MultiJobExecutors(tasks);multiJobExecutors.execute();}
}
執行結果
xx0
1472706027197
I
xx1
1472706027197
love
xx2
1472706027197
you
xx3
1472706027197
,
xx4
1472706027197
its
xx5
1472706027198
not
xx6
1472706027198
true
it's over