2018.12.12更新
在學習了CyclicBarrier之后發現,CyclicBarrier也可以實現跟CountDownLatch類似的功能,只需要在它的parties中多設置一個數,將主線程加入等待隊列就可以了:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
|
public static void main(String[] args) { ExecutorService pool = Executors.newCachedThreadPool(); int size = 3 ; // 設置參數時,線程實際執行數size+1,將main線程也加到等待隊列中 CyclicBarrier cyclicBarrier = new CyclicBarrier(size + 1 ); for ( int i = 0 ; i < size; i++) { int index = i; pool.submit(() -> { try { TimeUnit.SECONDS.sleep(index); System.out.println( "第" + index + "位運動員準備好了" ); cyclicBarrier.await(); } catch (Exception e) { e.printStackTrace(); } }); } try { //主線程也加入等待 cyclicBarrier.await(); } catch (Exception e) { e.printStackTrace(); } System.out.println(size + "位運動員都準備好了,可以起跑!" ); } |
執行結果:
以下是原內容:
我在使用并發線程柵欄的時候發現了兩種,分別是CyclicBarrier 和CountDownLatch。對于兩者的對比的文章有很多,這里不再贅述。我來說下我的使用過程。
**需求:**有三位運動員,他們一起參加萬米賽跑,但是他們準備的時間不同,要等他們都準備好了再開始一起跑。
使用CyclicBarrier 實現:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
|
import java.util.concurrent.*; public class RunTest { public static void main(String[] args) { ExecutorService pool = Executors.newCachedThreadPool(); int size = 3 ; CyclicBarrier cyclicBarrier = new CyclicBarrier(size, () -> { System.out.println(size + "位運動員都準備好了,可以起跑!" ); pool.shutdownNow(); }); for ( int i = 0 ; i < size; i++) { int index = i; pool.submit(() -> { try { TimeUnit.SECONDS.sleep(index); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println( "第" + index + "位運動員準備好了" ); try { cyclicBarrier.await(); } catch (InterruptedException | BrokenBarrierException e) { e.printStackTrace(); } }); } } } |
結果:
可以看到,三位運動員準備的時間分別是1s,2s,3s。系統等到他們都準備好了,再發出起跑的信號。在這里CyclicBarrier 做法是在自己的構造器中new了一個runnable,等待其他線程都執行完,再執行此runnable中的代碼。
我們再看看CountDownLatch怎么實現:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
|
import java.util.concurrent.*; public class RunTest { public static void main(String[] args) throws InterruptedException { ExecutorService pool = Executors.newCachedThreadPool(); CountDownLatch countDownLatch = new CountDownLatch( 3 ); int size = 3 ; for ( int i = 0 ; i < size; i++) { int index = i; pool.submit(() -> { try { TimeUnit.SECONDS.sleep(index); countDownLatch.countDown(); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println( "第" + index + "位運動員準備好了" ); }); } countDownLatch.await(); System.out.println(size + "位運動員都準備好了,可以起跑!" ); } } |
結果同上:
我們可以看到,countDownLatch是采取阻塞主線程的方法實現了線程的統一。他內部有一個計數器,我們在執行完一次線程任務的時候需要手動的減一個數,在主線程中使用 **countDownLatch.await()**監控計數器的狀態,知道計數器計到0為止,再執行主線程的代碼。
在實際的開發中,我個人比較傾向于第二種方法,因為使用起來簡單,完全滿足我的需求。
以上這篇基于CyclicBarrier和CountDownLatch的使用區別說明就是小編分享給大家的全部內容了,希望能給大家一個參考,也希望大家多多支持服務器之家。
原文鏈接:https://blog.csdn.net/xqnode/article/details/81867857