ITeye博客

Java并发编程: CyclicBarrier让多线程齐步走

iaspecwang · 2013-08-24 08:16 · java线程 · 企业架构 · Markdown

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

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

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

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

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

Java代码  收藏代码

  1. /**
  2. * A synchronization aid that allows a set of threads to all wait for
  3. * each other to reach a common barrier point.  CyclicBarriers are
  4. * useful in programs involving a fixed sized party of threads that
  5. * must occasionally wait for each other. The barrier is called
  6. * [i]cyclic[/i] because it can be re-used after the waiting threads
  7. * are released.
  8. *
  9. * <p>A <tt>CyclicBarrier</tt> 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类内容如下: 

 

Java代码  收藏代码

  1. /*
  2. * @(#)CyclicBarrier.java   1.12 06/03/30
  3. *
  4. * Copyright 2006 Sun Microsystems, Inc. All rights reserved.
  5. * SUN PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
  6. */
  7. package java.util.concurrent;
  8. import java.util.concurrent.locks.*;
  9. /**
  10. * A synchronization aid that allows a set of threads to all wait for
  11. * each other to reach a common barrier point.  CyclicBarriers are
  12. * useful in programs involving a fixed sized party of threads that
  13. * must occasionally wait for each other. The barrier is called
  14. * [i]cyclic[/i] because it can be re-used after the waiting threads
  15. * are released.
  16. *
  17. * <p>A <tt>CyclicBarrier</tt> supports an optional {@link Runnable} command
  18. * that is run once per barrier point, after the last thread in the party
  19. * arrives, but before any threads are released.
  20. * This [i]barrier action[/i] is useful
  21. * for updating shared-state before any of the parties continue.
  22. *
  23. * <p><b>Sample usage:</b> Here is an example of
  24. *  using a barrier in a parallel decomposition design:
  25. * <pre>
  26. * class Solver {
  27. *   final int N;
  28. *   final float[][] data;
  29. *   final CyclicBarrier barrier;
  30. *
  31. *   class Worker implements Runnable {
  32. *     int myRow;
  33. *     Worker(int row) { myRow = row; }
  34. *     public void run() {
  35. *       while (!done()) {
  36. *         processRow(myRow);
  37. *
  38. *         try {
  39. *           barrier.await();
  40. *         } catch (InterruptedException ex) {
  41. *           return;
  42. *         } catch (BrokenBarrierException ex) {
  43. *           return;
  44. *         }
  45. *       }
  46. *     }
  47. *   }
  48. *
  49. *   public Solver(float[][] matrix) {
  50. *     data = matrix;
  51. *     N = matrix.length;
  52. *     barrier = new CyclicBarrier(N,
  53. *                                 new Runnable() {
  54. *                                   public void run() {
  55. *                                     mergeRows(...);
  56. *                                   }
  57. *                                 });
  58. *     for (int i = 0; i < N; ++i)
  59. *       new Thread(new Worker(i)).start();
  60. *
  61. *     waitUntilDone();
  62. *   }
  63. * }
  64. * </pre>
  65. * Here, each worker thread processes a row of the matrix then waits at the
  66. * barrier until all rows have been processed. When all rows are processed
  67. * the supplied {@link Runnable} barrier action is executed and merges the
  68. * rows. If the merger
  69. * determines that a solution has been found then <tt>done()</tt> will return
  70. * <tt>true</tt> and each worker will terminate.
  71. *
  72. * <p>If the barrier action does not rely on the parties being suspended when
  73. * it is executed, then any of the threads in the party could execute that
  74. * action when it is released. To facilitate this, each invocation of
  75. * {@link #await} returns the arrival index of that thread at the barrier.
  76. * You can then choose which thread should execute the barrier action, for
  77. * example:
  78. * <pre>  if (barrier.await() == 0) {
  79. *     // log the completion of this iteration
  80. *   }</pre>
  81. *
  82. * <p>The <tt>CyclicBarrier</tt> uses an all-or-none breakage model
  83. * for failed synchronization attempts: If a thread leaves a barrier
  84. * point prematurely because of interruption, failure, or timeout, all
  85. * other threads waiting at that barrier point will also leave
  86. * abnormally via {@link BrokenBarrierException} (or
  87. * {@link InterruptedException} if they too were interrupted at about
  88. * the same time).
  89. *
  90. * <p>Memory consistency effects: Actions in a thread prior to calling
  91. * {@code await()}
  92. * [url=package-summary.html#MemoryVisibility]<i>happen-before</i>[/url]
  93. * actions that are part of the barrier action, which in turn
  94. * <i>happen-before</i> actions following a successful return from the
  95. * corresponding {@code await()} in other threads.
  96. *
  97. * @since 1.5
  98. * @see CountDownLatch
  99. *
  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 <tt>count</tt> 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 > 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 <= 0L) {
  207. breakBarrier();
  208. throw new TimeoutException();
  209. }
  210. }
  211. } finally {
  212. lock.unlock();
  213. }
  214. }
  215. /**
  216. * Creates a new <tt>CyclicBarrier</tt> 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 <= 0) throw new IllegalArgumentException();
  229. this.parties = parties;
  230. this.count = parties;
  231. this.barrierCommand = barrierAction;
  232. }
  233. /**
  234. * Creates a new <tt>CyclicBarrier</tt> 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. * <tt>await</tt> on this barrier.
  256. *
  257. * <p>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. * <li>The last thread arrives; or
  262. * <li>Some other thread {@linkplain Thread#interrupt interrupts}
  263. * the current thread; or
  264. * <li>Some other thread {@linkplain Thread#interrupt interrupts}
  265. * one of the other waiting threads; or
  266. * <li>Some other thread times out while waiting for barrier; or
  267. * <li>Some other thread invokes {@link #reset} on this barrier.
  268. * [/list]
  269. *
  270. * <p>If the current thread:
  271. * [list]
  272. * <li>has its interrupted status set on entry to this method; or
  273. * <li>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. * <p>If the barrier is {@link #reset} while any thread is waiting,
  279. * or if the barrier {@linkplain #isBroken is broken} when
  280. * <tt>await</tt> is invoked, or while any thread is waiting, then
  281. * {@link BrokenBarrierException} is thrown.
  282. *
  283. * <p>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. * <p>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. *         <tt>{@link #getParties()} - 1</tt> 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. * <tt>await</tt> on this barrier, or the specified waiting time elapses.
  317. *
  318. * <p>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. * <li>The last thread arrives; or
  323. * <li>The specified timeout elapses; or
  324. * <li>Some other thread {@linkplain Thread#interrupt interrupts}
  325. * the current thread; or
  326. * <li>Some other thread {@linkplain Thread#interrupt interrupts}
  327. * one of the other waiting threads; or
  328. * <li>Some other thread times out while waiting for barrier; or
  329. * <li>Some other thread invokes {@link #reset} on this barrier.
  330. * [/list]
  331. *
  332. * <p>If the current thread:
  333. * [list]
  334. * <li>has its interrupted status set on entry to this method; or
  335. * <li>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. * <p>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. * <p>If the barrier is {@link #reset} while any thread is waiting,
  345. * or if the barrier {@linkplain #isBroken is broken} when
  346. * <tt>await</tt> is invoked, or while any thread is waiting, then
  347. * {@link BrokenBarrierException} is thrown.
  348. *
  349. * <p>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. * <p>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. *         <tt>{@link #getParties()} - 1</tt> 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代码  收藏代码

  1. package my.concurrent.cyclicbarrier;
  2. import java.util.concurrent.BrokenBarrierException;
  3. import java.util.concurrent.CyclicBarrier;
  4. public class TeamGroup implements Runnable {
  5. private final CyclicBarrier barrier;
  6. private int groupNumber;
  7. /**
  8. * @param barrier
  9. * @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代码  收藏代码

  1. package my.concurrent.cyclicbarrier;
  2. import java.util.concurrent.CyclicBarrier;
  3. import java.util.concurrent.ExecutorService;
  4. import java.util.concurrent.Executors;
  5. public class CyclicBarrierTest {
  6. private static final int THREAD_SLEEP_MILLIS = 6000;
  7. /** 旅游小数的个数 */
  8. private static final int NUMBER_OF_GROUPS = 6;
  9. /** 观光是否结束的标识 */
  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 <= 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 <= 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为止。 

 

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

 

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

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

 

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

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

评论(0)

暂无评论。

评论功能维护中,当前仅展示历史评论。