---
title: "Java并发编程: CyclicBarrier让多线程齐步走"
author: "iaspecwang"
date: "2013-08-24T08:16:29Z"
tags: []
categories: ["企业架构"]
slug: "java-cyclicbarrier"
draft: false
lastmod: "2013-08-24T08:16:29Z"
id: 1929700
url: "https://iaspecwang.iteye.com/blog/1929700"
---

以前在&lt;&lt;编写高质量代码－改善Java程序的151个建议&gt;&gt;一书中看到有一节的标题是“CyclicBarrier让多线程齐步走”，觉得这标题挺不错的，所以在写这篇博文的时候也采用了这个名字。 

本文首先会介绍CyclicBarrier辅助工具类，其次将用CyclicBarrier工具类来完成一个实例，最后将给出CyclicBarrier和CountDownLatch的几点比较。 

之前关于CountDownLatch的博文，请参考如下链接：   
**Java并发编程: 使用CountDownLatch协调子线程** -   
[http://mouselearnjava.iteye.com/blog/1915438](http://mouselearnjava.iteye.com/blog/1915438) 

**1. CyclicBarrier工具类介绍。**   
CyclicBarrier是一个同步辅助工具类，它允许一组线程相互等待，直到到达一个公共的栏栅点。CyclicBarriers对于那些包含一组固定大小线程，并且这些线程必须不时地相互等待的程序非常有用。之所以将其称之为循环的Barrier是因为该Barrier在等待的线程释放之后可以重用。   
CyclicBarrier 支持一个可选的 Runnable 命令，在一组线程中的最后一个线程到达之后（但在释放所有线程之前），该命令只在每个屏障点运行一次。若在继续所有参与线程之前更新共享状态，此屏障操作 很有用。 

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

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

01. /\**
02. * A synchronization aid that allows a set of threads to all wait for
03. * each other to reach a common barrier point.  CyclicBarriers are
04. * useful in programs involving a fixed sized party of threads that
05. * must occasionally wait for each other. The barrier is called
06. * \[i]cyclic\[/i] because it can be re-used after the waiting threads
07. * are released.
08. \*
09. * &lt;p&gt;A &lt;tt&gt;CyclicBarrier&lt;/tt&gt; supports an optional {@link Runnable} command
10. * that is run once per barrier point, after the last thread in the party
11. * arrives, but before any threads are released.
12. * This \[i]barrier action\[/i] is useful
13. * for updating shared-state before any of the parties continue.
14. \*/

**CyclicBarrier**采用**Condition**和**Lock**来完成线程之间的同步。相关的类图是CyclicBarrier类内容如下： 

![](http://dl2.iteye.com/upload/attachment/0087/7215/b8936438-5a59-31bb-bd7e-96492d9506f9.jpg) 

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

001. /*
002. * @(#)CyclicBarrier.java   1.12 06/03/30
003. \*
004. * Copyright 2006 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. /\**
010. * A synchronization aid that allows a set of threads to all wait for
011. * each other to reach a common barrier point.  CyclicBarriers are
012. * useful in programs involving a fixed sized party of threads that
013. * must occasionally wait for each other. The barrier is called
014. * \[i]cyclic\[/i] because it can be re-used after the waiting threads
015. * are released.
016. \*
017. * &lt;p&gt;A &lt;tt&gt;CyclicBarrier&lt;/tt&gt; supports an optional {@link Runnable} command
018. * that is run once per barrier point, after the last thread in the party
019. * arrives, but before any threads are released.
020. * This \[i]barrier action\[/i] is useful
021. * for updating shared-state before any of the parties continue.
022. \*
023. * &lt;p&gt;&lt;b&gt;Sample usage:&lt;/b&gt; Here is an example of
024. *  using a barrier in a parallel decomposition design:
025. * &lt;pre&gt;
026. * class Solver {
027. *   final int N;
028. *   final float\[]\[] data;
029. *   final CyclicBarrier barrier;
030. \*
031. *   class Worker implements Runnable {
032. *     int myRow;
033. *     Worker(int row) { myRow = row; }
034. *     public void run() {
035. *       while (!done()) {
036. *         processRow(myRow);
037. \*
038. *         try {
039. *           barrier.await();
040. *         } catch (InterruptedException ex) {
041. *           return;
042. *         } catch (BrokenBarrierException ex) {
043. *           return;
044. *         }
045. *       }
046. *     }
047. *   }
048. \*
049. *   public Solver(float\[]\[] matrix) {
050. *     data = matrix;
051. *     N = matrix.length;
052. *     barrier = new CyclicBarrier(N,
053. *                                 new Runnable() {
054. *                                   public void run() {
055. *                                     mergeRows(...);
056. *                                   }
057. *                                 });
058. *     for (int i = 0; i &lt; N; ++i)
059. *       new Thread(new Worker(i)).start();
060. \*
061. *     waitUntilDone();
062. *   }
063. * }
064. * &lt;/pre&gt;
065. * Here, each worker thread processes a row of the matrix then waits at the
066. * barrier until all rows have been processed. When all rows are processed
067. * the supplied {@link Runnable} barrier action is executed and merges the
068. * rows. If the merger
069. * determines that a solution has been found then &lt;tt&gt;done()&lt;/tt&gt; will return
070. * &lt;tt&gt;true&lt;/tt&gt; and each worker will terminate.
071. \*
072. * &lt;p&gt;If the barrier action does not rely on the parties being suspended when
073. * it is executed, then any of the threads in the party could execute that
074. * action when it is released. To facilitate this, each invocation of
075. * {@link #await} returns the arrival index of that thread at the barrier.
076. * You can then choose which thread should execute the barrier action, for
077. * example:
078. * &lt;pre&gt;  if (barrier.await() == 0) {
079. *     // log the completion of this iteration
080. *   }&lt;/pre&gt;
081. \*
082. * &lt;p&gt;The &lt;tt&gt;CyclicBarrier&lt;/tt&gt; uses an all-or-none breakage model
083. * for failed synchronization attempts: If a thread leaves a barrier
084. * point prematurely because of interruption, failure, or timeout, all
085. * other threads waiting at that barrier point will also leave
086. * abnormally via {@link BrokenBarrierException} (or
087. * {@link InterruptedException} if they too were interrupted at about
088. * the same time).
089. \*
090. * &lt;p&gt;Memory consistency effects: Actions in a thread prior to calling
091. * {@code await()}
092. * \[url=package-summary.html#MemoryVisibility]&lt;i&gt;happen-before&lt;/i&gt;\[/url]
093. * actions that are part of the barrier action, which in turn
094. * &lt;i&gt;happen-before&lt;/i&gt; actions following a successful return from the
095. * corresponding {@code await()} in other threads.
096. \*
097. * @since 1.5
098. * @see CountDownLatch
099. \*
100. * @author Doug Lea
101. \*/
102. public class CyclicBarrier {
103. /\**
104. * Each use of the barrier is represented as a generation instance.
105. * The generation changes whenever the barrier is tripped, or
106. * is reset. There can be many generations associated with threads
107. * using the barrier - due to the non-deterministic way the lock
108. * may be allocated to waiting threads - but only one of these
109. * can be active at a time (the one to which &lt;tt&gt;count&lt;/tt&gt; applies)
110. * and all the rest are either broken or tripped.
111. * There need not be an active generation if there has been a break
112. * but no subsequent reset.
113. \*/
114. private static class Generation {
115. boolean broken = false;
116. }
117. /\** The lock for guarding barrier entry \*/
118. private final ReentrantLock lock = new ReentrantLock();
119. /\** Condition to wait on until tripped \*/
120. private final Condition trip = lock.newCondition();
121. /\** The number of parties \*/
122. private final int parties;
123. /* The command to run when tripped \*/
124. private final Runnable barrierCommand;
125. /\** The current generation \*/
126. private Generation generation = new Generation();
127. /\**
128. * Number of parties still waiting. Counts down from parties to 0
129. * on each generation.  It is reset to parties on each new
130. * generation or when broken.
131. \*/
132. private int count;
133. /\**
134. * Updates state on barrier trip and wakes up everyone.
135. * Called only while holding lock.
136. \*/
137. private void nextGeneration() {
138. // signal completion of last generation
139. trip.signalAll();
140. // set up next generation
141. count = parties;
142. generation = new Generation();
143. }
144. /\**
145. * Sets current barrier generation as broken and wakes up everyone.
146. * Called only while holding lock.
147. \*/
148. private void breakBarrier() {
149. generation.broken = true;
150. count = parties;
151. trip.signalAll();
152. }
153. /\**
154. * Main barrier code, covering the various policies.
155. \*/
156. private int dowait(boolean timed, long nanos)
157. throws InterruptedException, BrokenBarrierException,
158. TimeoutException {
159. final ReentrantLock lock = this.lock;
160. lock.lock();
161. try {
162. final Generation g = generation;
163. if (g.broken)
164. throw new BrokenBarrierException();
165. if (Thread.interrupted()) {
166. breakBarrier();
167. throw new InterruptedException();
168. }
169. int index = --count;
170. if (index == 0) {  // tripped
171. boolean ranAction = false;
172. try {
173. final Runnable command = barrierCommand;
174. if (command != null)
175. command.run();
176. ranAction = true;
177. nextGeneration();
178. return 0;
179. } finally {
180. if (!ranAction)
181. breakBarrier();
182. }
183. }
184. // loop until tripped, broken, interrupted, or timed out
185. for (;;) {
186. try {
187. if (!timed)
188. trip.await();
189. else if (nanos &gt; 0L)
190. nanos = trip.awaitNanos(nanos);
191. } catch (InterruptedException ie) {
192. if (g == generation && ! g.broken) {
193. breakBarrier();
194. throw ie;
195. } else {
196. // We're about to finish waiting even if we had not
197. // been interrupted, so this interrupt is deemed to
198. // "belong" to subsequent execution.
199. Thread.currentThread().interrupt();
200. }
201. }
202. if (g.broken)
203. throw new BrokenBarrierException();
204. if (g != generation)
205. return index;
206. if (timed && nanos &lt;= 0L) {
207. breakBarrier();
208. throw new TimeoutException();
209. }
210. }
211. } finally {
212. lock.unlock();
213. }
214. }
215. /\**
216. * Creates a new &lt;tt&gt;CyclicBarrier&lt;/tt&gt; that will trip when the
217. * given number of parties (threads) are waiting upon it, and which
218. * will execute the given barrier action when the barrier is tripped,
219. * performed by the last thread entering the barrier.
220. \*
221. * @param parties the number of threads that must invoke {@link #await}
222. *        before the barrier is tripped
223. * @param barrierAction the command to execute when the barrier is
224. *        tripped, or {@code null} if there is no action
225. * @throws IllegalArgumentException if {@code parties} is less than 1
226. \*/
227. public CyclicBarrier(int parties, Runnable barrierAction) {
228. if (parties &lt;= 0) throw new IllegalArgumentException();
229. this.parties = parties;
230. this.count = parties;
231. this.barrierCommand = barrierAction;
232. }
233. /\**
234. * Creates a new &lt;tt&gt;CyclicBarrier&lt;/tt&gt; that will trip when the
235. * given number of parties (threads) are waiting upon it, and
236. * does not perform a predefined action when the barrier is tripped.
237. \*
238. * @param parties the number of threads that must invoke {@link #await}
239. *        before the barrier is tripped
240. * @throws IllegalArgumentException if {@code parties} is less than 1
241. \*/
242. public CyclicBarrier(int parties) {
243. this(parties, null);
244. }
245. /\**
246. * Returns the number of parties required to trip this barrier.
247. \*
248. * @return the number of parties required to trip this barrier
249. \*/
250. public int getParties() {
251. return parties;
252. }
253. /\**
254. * Waits until all {@linkplain #getParties parties} have invoked
255. * &lt;tt&gt;await&lt;/tt&gt; on this barrier.
256. \*
257. * &lt;p&gt;If the current thread is not the last to arrive then it is
258. * disabled for thread scheduling purposes and lies dormant until
259. * one of the following things happens:
260. * \[list]
261. * &lt;li&gt;The last thread arrives; or
262. * &lt;li&gt;Some other thread {@linkplain Thread#interrupt interrupts}
263. * the current thread; or
264. * &lt;li&gt;Some other thread {@linkplain Thread#interrupt interrupts}
265. * one of the other waiting threads; or
266. * &lt;li&gt;Some other thread times out while waiting for barrier; or
267. * &lt;li&gt;Some other thread invokes {@link #reset} on this barrier.
268. * \[/list]
269. \*
270. * &lt;p&gt;If the current thread:
271. * \[list]
272. * &lt;li&gt;has its interrupted status set on entry to this method; or
273. * &lt;li&gt;is {@linkplain Thread#interrupt interrupted} while waiting
274. * \[/list]
275. * then {@link InterruptedException} is thrown and the current thread's
276. * interrupted status is cleared.
277. \*
278. * &lt;p&gt;If the barrier is {@link #reset} while any thread is waiting,
279. * or if the barrier {@linkplain #isBroken is broken} when
280. * &lt;tt&gt;await&lt;/tt&gt; is invoked, or while any thread is waiting, then
281. * {@link BrokenBarrierException} is thrown.
282. \*
283. * &lt;p&gt;If any thread is {@linkplain Thread#interrupt interrupted} while waiting,
284. * then all other waiting threads will throw
285. * {@link BrokenBarrierException} and the barrier is placed in the broken
286. * state.
287. \*
288. * &lt;p&gt;If the current thread is the last thread to arrive, and a
289. * non-null barrier action was supplied in the constructor, then the
290. * current thread runs the action before allowing the other threads to
291. * continue.
292. * If an exception occurs during the barrier action then that exception
293. * will be propagated in the current thread and the barrier is placed in
294. * the broken state.
295. \*
296. * @return the arrival index of the current thread, where index
297. *         &lt;tt&gt;{@link #getParties()} - 1&lt;/tt&gt; indicates the first
298. *         to arrive and zero indicates the last to arrive
299. * @throws InterruptedException if the current thread was interrupted
300. *         while waiting
301. * @throws BrokenBarrierException if \[i]another\[/i] thread was
302. *         interrupted or timed out while the current thread was
303. *         waiting, or the barrier was reset, or the barrier was
304. *         broken when {@code await} was called, or the barrier
305. *         action (if present) failed due an exception.
306. \*/
307. public int await() throws InterruptedException, BrokenBarrierException {
308. try {
309. return dowait(false, 0L);
310. } catch (TimeoutException toe) {
311. throw new Error(toe); // cannot happen;
312. }
313. }
314. /\**
315. * Waits until all {@linkplain #getParties parties} have invoked
316. * &lt;tt&gt;await&lt;/tt&gt; on this barrier, or the specified waiting time elapses.
317. \*
318. * &lt;p&gt;If the current thread is not the last to arrive then it is
319. * disabled for thread scheduling purposes and lies dormant until
320. * one of the following things happens:
321. * \[list]
322. * &lt;li&gt;The last thread arrives; or
323. * &lt;li&gt;The specified timeout elapses; or
324. * &lt;li&gt;Some other thread {@linkplain Thread#interrupt interrupts}
325. * the current thread; or
326. * &lt;li&gt;Some other thread {@linkplain Thread#interrupt interrupts}
327. * one of the other waiting threads; or
328. * &lt;li&gt;Some other thread times out while waiting for barrier; or
329. * &lt;li&gt;Some other thread invokes {@link #reset} on this barrier.
330. * \[/list]
331. \*
332. * &lt;p&gt;If the current thread:
333. * \[list]
334. * &lt;li&gt;has its interrupted status set on entry to this method; or
335. * &lt;li&gt;is {@linkplain Thread#interrupt interrupted} while waiting
336. * \[/list]
337. * then {@link InterruptedException} is thrown and the current thread's
338. * interrupted status is cleared.
339. \*
340. * &lt;p&gt;If the specified waiting time elapses then {@link TimeoutException}
341. * is thrown. If the time is less than or equal to zero, the
342. * method will not wait at all.
343. \*
344. * &lt;p&gt;If the barrier is {@link #reset} while any thread is waiting,
345. * or if the barrier {@linkplain #isBroken is broken} when
346. * &lt;tt&gt;await&lt;/tt&gt; is invoked, or while any thread is waiting, then
347. * {@link BrokenBarrierException} is thrown.
348. \*
349. * &lt;p&gt;If any thread is {@linkplain Thread#interrupt interrupted} while
350. * waiting, then all other waiting threads will throw {@link
351. * BrokenBarrierException} and the barrier is placed in the broken
352. * state.
353. \*
354. * &lt;p&gt;If the current thread is the last thread to arrive, and a
355. * non-null barrier action was supplied in the constructor, then the
356. * current thread runs the action before allowing the other threads to
357. * continue.
358. * If an exception occurs during the barrier action then that exception
359. * will be propagated in the current thread and the barrier is placed in
360. * the broken state.
361. \*
362. * @param timeout the time to wait for the barrier
363. * @param unit the time unit of the timeout parameter
364. * @return the arrival index of the current thread, where index
365. *         &lt;tt&gt;{@link #getParties()} - 1&lt;/tt&gt; indicates the first
366. *         to arrive and zero indicates the last to arrive
367. * @throws InterruptedException if the current thread was interrupted
368. *         while waiting
369. * @throws TimeoutException if the specified timeout elapses
370. * @throws BrokenBarrierException if \[i]another\[/i] thread was
371. *         interrupted or timed out while the current thread was
372. *         waiting, or the barrier was reset, or the barrier was broken
373. *         when {@code await} was called, or the barrier action (if
374. *         present) failed due an exception
375. \*/
376. public int await(long timeout, TimeUnit unit)
377. throws InterruptedException,
378. BrokenBarrierException,
379. TimeoutException {
380. return dowait(true, unit.toNanos(timeout));
381. }
382. /\**
383. * Queries if this barrier is in a broken state.
384. \*
385. * @return {@code true} if one or more parties broke out of this
386. *         barrier due to interruption or timeout since
387. *         construction or the last reset, or a barrier action
388. *         failed due to an exception; {@code false} otherwise.
389. \*/
390. public boolean isBroken() {
391. final ReentrantLock lock = this.lock;
392. lock.lock();
393. try {
394. return generation.broken;
395. } finally {
396. lock.unlock();
397. }
398. }
399. /\**
400. * Resets the barrier to its initial state.  If any parties are
401. * currently waiting at the barrier, they will return with a
402. * {@link BrokenBarrierException}. Note that resets \[i]after\[/i]
403. * a breakage has occurred for other reasons can be complicated to
404. * carry out; threads need to re-synchronize in some other way,
405. * and choose one to perform the reset.  It may be preferable to
406. * instead create a new barrier for subsequent use.
407. \*/
408. public void reset() {
409. final ReentrantLock lock = this.lock;
410. lock.lock();
411. try {
412. breakBarrier();   // break the current generation
413. nextGeneration(); // start a new generation
414. } finally {
415. lock.unlock();
416. }
417. }
418. /\**
419. * Returns the number of parties currently waiting at the barrier.
420. * This method is primarily useful for debugging and assertions.
421. \*
422. * @return the number of parties currently blocked in {@link #await}
423. \*/
424. public int getNumberWaiting() {
425. final ReentrantLock lock = this.lock;
426. lock.lock();
427. try {
428. return parties - count;
429. } finally {
430. lock.unlock();
431. }
432. }
433. }

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

CyclicBarrier可以让所有线程都处于等待状态(阻塞)，然后在满足条件的情况下继续执行。打个比方： 几个小组包一辆车去旅游，一天行程包括上午小组自由活动和下午自由活动：各个小组早上自由活动，但是11点半大巴车上集合，然后吃饭并赶赴下一个景区。   
各个小组下午自由活动，但是要5点半大巴车上集合，然后一起回去。 

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

01. package my.concurrent.cyclicbarrier;
02. import java.util.concurrent.BrokenBarrierException;
03. import java.util.concurrent.CyclicBarrier;
04. public class TeamGroup implements Runnable {
05. private final CyclicBarrier barrier;
06. private int groupNumber;
07. /\**
08. * @param barrier
09. * @param groupNumber
10. \*/
11. public TeamGroup(CyclicBarrier barrier, int groupNumber) {
12. this.barrier = barrier;
13. this.groupNumber = groupNumber;
14. }
15. public void run() {
16. try {
17. print();
18. barrier.await();
19. } catch (InterruptedException e) {
20. // TODO Auto-generated catch block
21. e.printStackTrace();
22. } catch (BrokenBarrierException e) {
23. // TODO Auto-generated catch block
24. e.printStackTrace();
25. }
26. }
27. private void print() {
28. System.out.println(String.format("第%d组完成该地景点浏览，并回到集合点", groupNumber));
29. }
30. }

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

01. package my.concurrent.cyclicbarrier;
02. import java.util.concurrent.CyclicBarrier;
03. import java.util.concurrent.ExecutorService;
04. import java.util.concurrent.Executors;
05. public class CyclicBarrierTest {
06. private static final int THREAD\_SLEEP\_MILLIS = 6000;
07. /\** 旅游小数的个数 \*/
08. private static final int NUMBER\_OF\_GROUPS = 6;
09. /\** 观光是否结束的标识 \*/
10. private static boolean tourOver = false;
11. public static void main(String\[] args) {
12. ExecutorService service = Executors
13. .newFixedThreadPool(NUMBER\_OF\_GROUPS);
14. CyclicBarrier cb = new CyclicBarrier(NUMBER\_OF\_GROUPS, new Runnable() {
15. public void run() {
16. /*
17. * 如果一天的游玩结束了，大家可以坐大巴回去了... ...
18. \*/
19. if (isTourOver()) {
20. System.out.println("各个小组都集合到大巴上，准备回家.. ...");
21. }
22. }
23. });
24. System.out.println("用CyclicBarrier辅助工具类模拟旅游过程中小组集合:：");
25. /*
26. * 上午各个小组自由活动，然后在某个点，比如11点半集合到大巴上。
27. \*/
28. tourInTheMorning(service, cb);
29. sleep(THREAD\_SLEEP\_MILLIS);
30. /*
31. * 调用reset方法，将barrier设置到初始化状态。
32. \*
33. * TODO://不知道这样的调用是否是合理的？
34. \*/
35. cb.reset();
36. /*
37. * 下午各个小组自由活动，然后在某个点，比如11点半集合到大巴上。
38. \*/
39. tourInTheAfternoon(service, cb);
40. /*
41. * 下午小组集合完毕后，一天的观光就结束了，将标志位记为true;
42. \*/
43. tourOver = true;
44. sleep(THREAD\_SLEEP\_MILLIS);
45. service.shutdown();
46. }
47. /\**
48. * @return the tourOver
49. \*/
50. public static boolean isTourOver() {
51. return tourOver;
52. }
53. /\**
54. * @param tourOver
55. *            the tourOver to set
56. \*/
57. public static void setTourOver(boolean tourOver) {
58. CyclicBarrierTest.tourOver = tourOver;
59. }
60. private static void tourInTheMorning(ExecutorService service,
61. final CyclicBarrier cb) {
62. System.out.println("早上自由玩... ... ");
63. for (int groupNumber = 1; groupNumber &lt;= NUMBER\_OF\_GROUPS; groupNumber++) {
64. service.execute(new TeamGroup(cb, groupNumber));
65. }
66. }
67. private static void tourInTheAfternoon(ExecutorService service,
68. final CyclicBarrier cb) {
69. System.out.println("下午自由玩... ... ");
70. for (int groupNumber = 1; groupNumber &lt;= NUMBER\_OF\_GROUPS; groupNumber++) {
71. service.execute(new TeamGroup(cb, groupNumber));
72. }
73. }
74. private static void sleep(long millis) {
75. try {
76. Thread.sleep(millis);
77. } catch (InterruptedException e) {
78. // TODO Auto-generated catch block
79. e.printStackTrace();
80. }
81. }
82. }

**某一次运行的结果如下：** 

用CyclicBarrier辅助工具类模拟旅游过程中小组集合:：   
早上自由玩... ...   
第1组完成该地景点浏览，并回到集合点   
第6组完成该地景点浏览，并回到集合点   
第2组完成该地景点浏览，并回到集合点   
第5组完成该地景点浏览，并回到集合点   
第4组完成该地景点浏览，并回到集合点   
第3组完成该地景点浏览，并回到集合点   
下午自由玩... ...   
第1组完成该地景点浏览，并回到集合点   
第3组完成该地景点浏览，并回到集合点   
第4组完成该地景点浏览，并回到集合点   
第5组完成该地景点浏览，并回到集合点   
第6组完成该地景点浏览，并回到集合点   
第2组完成该地景点浏览，并回到集合点   
各个小组都集合到大巴上，准备回家.. ... 

**3. CyclicBarrier vs. CountDownLatch** 

**相同点：**     
    两者都是用于**线程同步**的辅助工具类，都提供了**await**方法来达到线程等待。 

**不同点：**   
1\. 从类的实现上看：   
    CountDownLatch通过一个继承AbstractQueuedSynchronizer的内部类Sync来完成同步。   
    CyclicBarrier通过Condition和Lock来完成同步。   
2\. 从类的用途上看：   
    CountDownLatch： 一个或者是一部分线程，等待另外一部线程都完成操作。   
    CyclicBarrier： 所有线程互相等待完成。   
3\. 从适合场合来看：   
CountDownLatch中计数是不能被重置的。如果需要一个可以重置计数的版本，需要考虑使用CyclicBarrie。   
CountDownLatch适用于一次同步。当使用CountDownLatch时，任何线程允许多次调用countDown(). 那些调用了await()方法的线程将被阻塞，直到那些没有被阻塞线程调用countDown()使计数到达0为止。 

![](http://dl2.iteye.com/upload/attachment/0087/7217/c1a4c87c-57d8-3e25-92d5-43d94d029d79.jpg) 

**相反**，CyclicBarrier适用于多个同步点。例如：一组正在运算的线程，在进入下一个阶段计算之前需要同步。 

![](http://dl2.iteye.com/upload/attachment/0087/7219/9048f390-3096-3ed1-a8b6-80a7b55e26eb.jpg) 

与CountDownLatch不同，一个处于某个阶段的线程调用了await()方法将会被阻塞，直到所有属于这个阶段的线程都调用了await()方法为止。 

在CyclicBarrier中，如果一个线程由于中断，失败或者超时等原因，过早地离开了栅栏点，那么所有在栅栏点等待的其它线程也会通过BrokenBarrierException或者IterupedException异常地离开。 

![](http://dl2.iteye.com/upload/attachment/0087/7221/915128c7-e04c-3e5b-9f24-735dd965a1c6.jpg) 

4\. 从关注点上来看： **使用CountDownLatch时，它关注的一个线程或者多个线程需要在其它在一组线程完成操作之后，在去做一些事情**。比如：服务的启动等。**CyclicBarrier更加关注的是公共的栅栏点(Common Barrier point),关注的是这个点上的同步。这个点之前之后的事情并不需要太多的关注。**比如：一个并行计算需要分几个阶段完成，在一个阶段完成进入到下一个阶段之前，需要同步，这时候CyclicBarrie很适合。 

由于知识的原因，上述例子以及CountDownLatch和CyclicBarrier的比较上会存在不足，如果有问题请大家指正，也希望大家能够提供两者其它方面的不同之处，一起学习分享。