---
title: "Java并发编程: 使用CountDownLatch协调子线程"
author: "iaspecwang"
date: "2013-08-24T08:15:19Z"
tags: []
categories: ["企业架构"]
slug: "java-countdownlatch"
draft: false
lastmod: "2013-08-24T08:15:19Z"
id: 1929698
url: "https://iaspecwang.iteye.com/blog/1929698"
---

本文将介绍CountDownLatch工具类，并采用这个工具类给出一个实例。 

**1. CountDownLatch工具类介绍** 

CountDownLatch是一个同步工具类，它允许一个或多个线程处于等待状态直到在其它线程中运行的一组操作完成为止。CountDownLatch用一个给定的计数来实现初始化。Await方法会一直处于阻塞状态，直到countDown方法调用而使当前计数达到零。当计数为零之后，所有处于等待的线程将被释放，await的任何后续调用将立即返回。这种现象只出现一次，计数是不能被重置的。如果你需要一个可以重置计数的版本，需要考虑使用CyclicBarrie. 

上面的介绍来自于CountDownLatch类的注释。 

Java代码  [![收藏代码](http://mouselearnjava.iteye.com/images/icon_star.png)]()

01. /\**
02. * A synchronization aid that allows one or more threads to wait until
03. * a set of operations being performed in other threads completes.
04. \*
05. * &lt;p&gt;A {@code CountDownLatch} is initialized with a given \[i]count\[/i].
06. * The {@link #await await} methods block until the current count reaches
07. * zero due to invocations of the {@link #countDown} method, after which
08. * all waiting threads are released and any subsequent invocations of
09. * {@link #await await} return immediately.  This is a one-shot phenomenon
10. * -- the count cannot be reset.  If you need a version that resets the
11. * count, consider using a {@link CyclicBarrier}.
12. \*
13. \*/

**CountDownLatch**中定义了一个内部类**Sync**，该类继承**AbstractQueuedSynchronizer**。从代码中可以看出，**CountDownLatch的await,countDown以及getCount方法都调用了Sync的方法。**CountDownLatch工具类相关的类图以及详细代码如下： 

![](http://dl2.iteye.com/upload/attachment/0087/6209/49d9bf62-ac46-3a6a-ad5c-09a62acd0ea9.jpg) 

Java代码  [![收藏代码](http://mouselearnjava.iteye.com/images/icon_star.png)]()

001. /*
002. * @(#)CountDownLatch.java  1.5 04/02/09
003. \*
004. * Copyright 2004 Sun Microsystems, Inc. All rights reserved.
005. * SUN PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
006. \*/
007. package java.util.concurrent;
008. import java.util.concurrent.locks.\*;
009. import java.util.concurrent.atomic.\*;
010. /\**
011. * A synchronization aid that allows one or more threads to wait until
012. * a set of operations being performed in other threads completes.
013. \*
014. * &lt;p&gt;A &lt;tt&gt;CountDownLatch&lt;/tt&gt; is initialized with a given
015. * \[i]count\[/i].  The {@link #await await} methods block until the current
016. * {@link #getCount count} reaches zero due to invocations of the
017. * {@link #countDown} method, after which all waiting threads are
018. * released and any subsequent invocations of {@link #await await} return
019. * immediately. This is a one-shot phenomenon -- the count cannot be
020. * reset.  If you need a version that resets the count, consider using
021. * a {@link CyclicBarrier}.
022. \*
023. * &lt;p&gt;A &lt;tt&gt;CountDownLatch&lt;/tt&gt; is a versatile synchronization tool
024. * and can be used for a number of purposes.  A
025. * &lt;tt&gt;CountDownLatch&lt;/tt&gt; initialized with a count of one serves as a
026. * simple on/off latch, or gate: all threads invoking {@link #await await}
027. * wait at the gate until it is opened by a thread invoking {@link
028. * #countDown}.  A &lt;tt&gt;CountDownLatch&lt;/tt&gt; initialized to \[i]N\[/i]
029. * can be used to make one thread wait until \[i]N\[/i] threads have
030. * completed some action, or some action has been completed N times.
031. * &lt;p&gt;A useful property of a &lt;tt&gt;CountDownLatch&lt;/tt&gt; is that it
032. * doesn't require that threads calling &lt;tt&gt;countDown&lt;/tt&gt; wait for
033. * the count to reach zero before proceeding, it simply prevents any
034. * thread from proceeding past an {@link #await await} until all
035. * threads could pass.
036. \*
037. * &lt;p&gt;&lt;b&gt;Sample usage:&lt;/b&gt; Here is a pair of classes in which a group
038. * of worker threads use two countdown latches:
039. * \[list]
040. * &lt;li&gt;The first is a start signal that prevents any worker from proceeding
041. * until the driver is ready for them to proceed;
042. * &lt;li&gt;The second is a completion signal that allows the driver to wait
043. * until all workers have completed.
044. * \[/list]
045. \*
046. * &lt;pre&gt;
047. * class Driver { // ...
048. *   void main() throws InterruptedException {
049. *     CountDownLatch startSignal = new CountDownLatch(1);
050. *     CountDownLatch doneSignal = new CountDownLatch(N);
051. \*
052. *     for (int i = 0; i &lt; N; ++i) // create and start threads
053. *       new Thread(new Worker(startSignal, doneSignal)).start();
054. \*
055. *     doSomethingElse();            // don't let run yet
056. *     startSignal.countDown();      // let all threads proceed
057. *     doSomethingElse();
058. *     doneSignal.await();           // wait for all to finish
059. *   }
060. * }
061. \*
062. * class Worker implements Runnable {
063. *   private final CountDownLatch startSignal;
064. *   private final CountDownLatch doneSignal;
065. *   Worker(CountDownLatch startSignal, CountDownLatch doneSignal) {
066. *      this.startSignal = startSignal;
067. *      this.doneSignal = doneSignal;
068. *   }
069. *   public void run() {
070. *      try {
071. *        startSignal.await();
072. *        doWork();
073. *        doneSignal.countDown();
074. *      } catch (InterruptedException ex) {} // return;
075. *   }
076. \*
077. *   void doWork() { ... }
078. * }
079. \*
080. * &lt;/pre&gt;
081. \*
082. * &lt;p&gt;Another typical usage would be to divide a problem into N parts,
083. * describe each part with a Runnable that executes that portion and
084. * counts down on the latch, and queue all the Runnables to an
085. * Executor.  When all sub-parts are complete, the coordinating thread
086. * will be able to pass through await. (When threads must repeatedly
087. * count down in this way, instead use a {@link CyclicBarrier}.)
088. \*
089. * &lt;pre&gt;
090. * class Driver2 { // ...
091. *   void main() throws InterruptedException {
092. *     CountDownLatch doneSignal = new CountDownLatch(N);
093. *     Executor e = ...
094. \*
095. *     for (int i = 0; i &lt; N; ++i) // create and start threads
096. *       e.execute(new WorkerRunnable(doneSignal, i));
097. \*
098. *     doneSignal.await();           // wait for all to finish
099. *   }
100. * }
101. \*
102. * class WorkerRunnable implements Runnable {
103. *   private final CountDownLatch doneSignal;
104. *   private final int i;
105. *   WorkerRunnable(CountDownLatch doneSignal, int i) {
106. *      this.doneSignal = doneSignal;
107. *      this.i = i;
108. *   }
109. *   public void run() {
110. *      try {
111. *        doWork(i);
112. *        doneSignal.countDown();
113. *      } catch (InterruptedException ex) {} // return;
114. *   }
115. \*
116. *   void doWork() { ... }
117. * }
118. \*
119. * &lt;/pre&gt;
120. \*
121. * @since 1.5
122. * @author Doug Lea
123. \*/
124. public class CountDownLatch {
125. /\**
126. * Synchronization control For CountDownLatch.
127. * Uses AQS state to represent count.
128. \*/
129. private static final class Sync extends AbstractQueuedSynchronizer {
130. Sync(int count) {
131. setState(count);
132. }
133. int getCount() {
134. return getState();
135. }
136. public int tryAcquireShared(int acquires) {
137. return getState() == 0? 1 : -1;
138. }
139. public boolean tryReleaseShared(int releases) {
140. // Decrement count; signal when transition to zero
141. for (;;) {
142. int c = getState();
143. if (c == 0)
144. return false;
145. int nextc = c-1;
146. if (compareAndSetState(c, nextc))
147. return nextc == 0;
148. }
149. }
150. }
151. private final Sync sync;
152. /\**
153. * Constructs a &lt;tt&gt;CountDownLatch&lt;/tt&gt; initialized with the given
154. * count.
155. \*
156. * @param count the number of times {@link #countDown} must be invoked
157. * before threads can pass through {@link #await}.
158. \*
159. * @throws IllegalArgumentException if &lt;tt&gt;count&lt;/tt&gt; is less than zero.
160. \*/
161. public CountDownLatch(int count) {
162. if (count &lt; 0) throw new IllegalArgumentException("count &lt; 0");
163. this.sync = new Sync(count);
164. }
165. /\**
166. * Causes the current thread to wait until the latch has counted down to
167. * zero, unless the thread is {@link Thread#interrupt interrupted}.
168. \*
169. * &lt;p&gt;If the current {@link #getCount count} is zero then this method
170. * returns immediately.
171. * &lt;p&gt;If the current {@link #getCount count} is greater than zero then
172. * the current thread becomes disabled for thread scheduling
173. * purposes and lies dormant until one of two things happen:
174. * \[list]
175. * &lt;li&gt;The count reaches zero due to invocations of the
176. * {@link #countDown} method; or
177. * &lt;li&gt;Some other thread {@link Thread#interrupt interrupts} the current
178. * thread.
179. * \[/list]
180. * &lt;p&gt;If the current thread:
181. * \[list]
182. * &lt;li&gt;has its interrupted status set on entry to this method; or
183. * &lt;li&gt;is {@link Thread#interrupt interrupted} while waiting,
184. * \[/list]
185. * then {@link InterruptedException} is thrown and the current thread's
186. * interrupted status is cleared.
187. \*
188. * @throws InterruptedException if the current thread is interrupted
189. * while waiting.
190. \*/
191. public void await() throws InterruptedException {
192. sync.acquireSharedInterruptibly(1);
193. }
194. /\**
195. * Causes the current thread to wait until the latch has counted down to
196. * zero, unless the thread is {@link Thread#interrupt interrupted},
197. * or the specified waiting time elapses.
198. \*
199. * &lt;p&gt;If the current {@link #getCount count} is zero then this method
200. * returns immediately with the value &lt;tt&gt;true&lt;/tt&gt;.
201. \*
202. * &lt;p&gt;If the current {@link #getCount count} is greater than zero then
203. * the current thread becomes disabled for thread scheduling
204. * purposes and lies dormant until one of three things happen:
205. * \[list]
206. * &lt;li&gt;The count reaches zero due to invocations of the
207. * {@link #countDown} method; or
208. * &lt;li&gt;Some other thread {@link Thread#interrupt interrupts} the current
209. * thread; or
210. * &lt;li&gt;The specified waiting time elapses.
211. * \[/list]
212. * &lt;p&gt;If the count reaches zero then the method returns with the
213. * value &lt;tt&gt;true&lt;/tt&gt;.
214. * &lt;p&gt;If the current thread:
215. * \[list]
216. * &lt;li&gt;has its interrupted status set on entry to this method; or
217. * &lt;li&gt;is {@link Thread#interrupt interrupted} while waiting,
218. * \[/list]
219. * then {@link InterruptedException} is thrown and the current thread's
220. * interrupted status is cleared.
221. \*
222. * &lt;p&gt;If the specified waiting time elapses then the value &lt;tt&gt;false&lt;/tt&gt;
223. * is returned.
224. * If the time is
225. * less than or equal to zero, the method will not wait at all.
226. \*
227. * @param timeout the maximum time to wait
228. * @param unit the time unit of the &lt;tt&gt;timeout&lt;/tt&gt; argument.
229. * @return &lt;tt&gt;true&lt;/tt&gt; if the count reached zero  and &lt;tt&gt;false&lt;/tt&gt;
230. * if the waiting time elapsed before the count reached zero.
231. \*
232. * @throws InterruptedException if the current thread is interrupted
233. * while waiting.
234. \*/
235. public boolean await(long timeout, TimeUnit unit)
236. throws InterruptedException {
237. return sync.tryAcquireSharedNanos(1, unit.toNanos(timeout));
238. }
239. /\**
240. * Decrements the count of the latch, releasing all waiting threads if
241. * the count reaches zero.
242. * &lt;p&gt;If the current {@link #getCount count} is greater than zero then
243. * it is decremented. If the new count is zero then all waiting threads
244. * are re-enabled for thread scheduling purposes.
245. * &lt;p&gt;If the current {@link #getCount count} equals zero then nothing
246. * happens.
247. \*/
248. public void countDown() {
249. sync.releaseShared(1);
250. }
251. /\**
252. * Returns the current count.
253. * &lt;p&gt;This method is typically used for debugging and testing purposes.
254. * @return the current count.
255. \*/
256. public long getCount() {
257. return sync.getCount();
258. }
259. /\**
260. * Returns a string identifying this latch, as well as its state.
261. * The state, in brackets, includes the String
262. * "Count =" followed by the current count.
263. * @return a string identifying this latch, as well as its
264. * state
265. \*/
266. public String toString() {
267. return super.toString() + "\[Count = " + sync.getCount() + "]";
268. }
269. }

**2. CountDownLatch工具类的使用案例** 

CountDownLatch的作用是控制一个计数器，每个线程在运行完毕后执行countDown，表示自己运行结束，这对于多个子任务的计算特别有效，比如一个异步任务需要拆分成10个子任务执行，主任务必须知道子任务是否完成，所有子任务完成后才能进行合并计算，从而保证了一个主任务逻辑的正确性。(此段摘自于&lt;&lt;改善Java程序的151个建议&gt;&gt;, P254) 

CountDownLatch最重要的方法是countDown()和await()，前者主要是倒数一次，后者是等待倒数到0，如果没有到达0，就只有阻塞等待了。 

本实例主要**使用CountDownLatch工具类来实现10个线程对1~100的求和，每个线程对10个数进行求和。**第一个线程对1 – 10求和   
第二个线程对 11 – 20求和   
第三个线程对21 – 30 求和 

…..   
第十个线程对91 – 100求和。 

具体的代码如下： 

Java代码  [![收藏代码](http://mouselearnjava.iteye.com/images/icon_star.png)]()

01. package my.concurrent.countdown;
02. import java.util.concurrent.Callable;
03. import java.util.concurrent.CountDownLatch;
04. public class Calculator implements Callable&lt;Integer&gt; {
05. //开始信号
06. private final CountDownLatch startSignal;
07. //结束信号
08. private final CountDownLatch doneSignal;
09. private int groupNumber = 0;
10. /\**
11. * @param startSignal
12. * @param endSignal
13. * @param groupId
14. \*/
15. public Calculator(CountDownLatch startSignal, CountDownLatch doneSignal,
16. int groupNumber) {
17. this.startSignal = startSignal;
18. this.doneSignal = doneSignal;
19. this.groupNumber = groupNumber;
20. }
21. public Integer call() throws Exception {
22. startSignal.await();
23. Integer result = sum(groupNumber);
24. printCompleteInfor(groupNumber,result);
25. doneSignal.countDown();
26. return result;
27. }
28. private Integer sum(int groupNumber) {
29. if (groupNumber &lt; 1) {
30. throw new IllegalArgumentException();
31. }
32. int sum = 0;
33. int start = (groupNumber - 1) * 10 + 1;
34. int end = groupNumber * 10;
35. for (int i = start; i &lt;= end; i++) {
36. sum += i;
37. }
38. return sum;
39. }
40. private void printCompleteInfor(int groupNumber, int sum)
41. {
42. System.out.println(String.format("Group %d is finished, the sum in this gropu is %d", groupNumber, sum));
43. }
44. }

Java代码  [![收藏代码](http://mouselearnjava.iteye.com/images/icon_star.png)]()

01. package my.concurrent.countdown;
02. import java.util.ArrayList;
03. import java.util.List;
04. import java.util.concurrent.CountDownLatch;
05. import java.util.concurrent.ExecutionException;
06. import java.util.concurrent.ExecutorService;
07. import java.util.concurrent.Executors;
08. import java.util.concurrent.Future;
09. public class CountDownLatchTest {
10. public static void main(String\[] args) throws Exception {
11. /\**
12. * 1－100求和，分10个线程来计算，每个线程对10个数求和。
13. \*/
14. int numOfGroups = 10;
15. CountDownLatch startSignal = new CountDownLatch(1);
16. CountDownLatch doneSignal = new CountDownLatch(numOfGroups);
17. ExecutorService service = Executors.newFixedThreadPool(numOfGroups);
18. List&lt;Future&lt;Integer&gt;&gt; futures = new ArrayList&lt;Future&lt;Integer&gt;&gt;();
19. submit(futures, numOfGroups, service, startSignal, doneSignal);
20. /\**
21. * 开始，让所有的求和计算线程运行
22. \*/
23. startSignal.countDown();
24. /\**
25. * 阻塞，知道所有计算线程完成计算
26. \*/
27. doneSignal.await();
28. shutdown(service);
29. printResult(futures);
30. }
31. private static void submit(List&lt;Future&lt;Integer&gt;&gt; futures, int numOfGroups,
32. ExecutorService service, CountDownLatch startSignal,
33. CountDownLatch doneSignal) {
34. for (int groupNumber = 1; groupNumber &lt;= numOfGroups; groupNumber++) {
35. futures.add(service.submit(new Calculator(startSignal, doneSignal,
36. groupNumber)));
37. }
38. }
39. private static int getResult(List&lt;Future&lt;Integer&gt;&gt; futures)
40. throws InterruptedException, ExecutionException {
41. int result = 0;
42. for (Future&lt;Integer&gt; f : futures) {
43. result += f.get();
44. }
45. return result;
46. }
47. private static void printResult(List&lt;Future&lt;Integer&gt;&gt; futures)
48. throws InterruptedException, ExecutionException {
49. System.out.println("\[1,100] Sum is :" + getResult(futures));
50. }
51. private static void shutdown(ExecutorService service)
52. {
53. service.shutdown();
54. }
55. }

一次的执行结果如下：   
Group 8 is finished, the sum in this gropu is 755   
Group 2 is finished, the sum in this gropu is 155   
Group 10 is finished, the sum in this gropu is 955   
Group 5 is finished, the sum in this gropu is 455   
Group 7 is finished, the sum in this gropu is 655   
Group 3 is finished, the sum in this gropu is 255   
Group 9 is finished, the sum in this gropu is 855   
Group 1 is finished, the sum in this gropu is 55   
Group 4 is finished, the sum in this gropu is 355   
Group 6 is finished, the sum in this gropu is 555   
\[1,100] Sum is :5050