1、CountDownLatch:
一個同步工具類,它允許一個或多個線程一直等待,直到其他線程的操作執行完后再執行。
2、ThreadPoolExecutor/ExecutorService:
線程池,使用線程池可以復用線程,降低頻繁創建線程造成的性能消耗,同時對線程的創建、啟動、停止、銷毀等操作更簡便。
3、使用場景舉例:
年末公司組織團建,要求每一位員工周六上午8點到公司門口集合,統一乘坐公司所租大巴前往目的地。
在這個案例中,公司作為主線程,員工作為子線程。
4、代碼示例:
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
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
|
package com.test.thread; import java.util.concurrent.CountDownLatch; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.LinkedBlockingQueue; import java.util.concurrent.ThreadPoolExecutor; import java.util.concurrent.TimeUnit; /** * @author javaloveiphone * @date 創建時間:2017年1月25日 上午10:59:11 * @Description: */ public class Company { public static void main(String[] args) throws InterruptedException { //員工數量 int count = 5 ; //創建計數器 //構造參數傳入的數量值代表的是latch.countDown()調用的次數 CountDownLatch latch = new CountDownLatch(count); //創建線程池,可以通過以下方式創建 //ThreadPoolExecutor threadPool = new ThreadPoolExecutor(1,1,60,TimeUnit.SECONDS,new LinkedBlockingQueue<Runnable>(count)); ExecutorService threadPool = Executors.newFixedThreadPool(count); System.out.println( "公司發送通知,每一位員工在周六早上8點到公司大門口集合" ); for ( int i = 0 ;i<count ;i++){ //將子線程添加進線程池執行 Thread.sleep( 10 ); threadPool.execute( new Employee(latch,i+ 1 )); } try { //阻塞當前線程,直到所有員工到達公司大門口之后才執行 latch.await(); // 使當前線程在鎖存器倒計數至零之前一直等待,除非線程被中斷或超出了指定的等待時間。 //latch.await(long timeout, TimeUnit unit) System.out.println( "所有員工已經到達公司大門口,大巴車發動,前往活動目的地。" ); } catch (InterruptedException e) { e.printStackTrace(); } finally { //最后關閉線程池,但執行以前提交的任務,不接受新任務 threadPool.shutdown(); //關閉線程池,停止所有正在執行的活動任務,暫停處理正在等待的任務,并返回等待執行的任務列表。 //threadPool.shutdownNow(); } } } //分布式工作線程 class Employee implements Runnable{ private CountDownLatch latch; private int employeeIndex; public Employee(CountDownLatch latch, int employeeIndex){ this .latch = latch; this .employeeIndex = employeeIndex; } @Override public void run() { try { System.out.println( "員工:" +employeeIndex+ ",正在前往公司大門口集合..." ); Thread.sleep( 10 ); System.out.println( "員工:" +employeeIndex+ ",已到達。" ); } catch (Exception e) { e.printStackTrace(); } finally { //當前計算工作已結束,計數器減一 latch.countDown(); try { Thread.sleep( 10 ); } catch (InterruptedException e) { e.printStackTrace(); } //執行coutDown()之后,繼續執行自己的工作,不受主線程的影響 System.out.println( "員工:" +employeeIndex+ ",吃飯、喝水、拍照。" ); } } } |
打印輸出結果如下:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
|
公司發送通知,每一位員工在周六早上 8 點到公司大門口集合 員工: 1 ,正在前往公司大門口集合... 員工: 1 ,已到達。 員工: 2 ,正在前往公司大門口集合... 員工: 2 ,已到達。 員工: 1 ,吃飯、喝水、拍照。 員工: 3 ,正在前往公司大門口集合... 員工: 2 ,吃飯、喝水、拍照。 員工: 3 ,已到達。 員工: 4 ,正在前往公司大門口集合... 員工: 3 ,吃飯、喝水、拍照。 員工: 4 ,已到達。 員工: 5 ,正在前往公司大門口集合... 員工: 4 ,吃飯、喝水、拍照。 員工: 5 ,已到達。 所有員工已經到達公司大門口,大巴車發動,前往活動目的地。 員工: 5 ,吃飯、喝水、拍照。 |
注意:
每一個員工到達之后,執行countDown()方法,直到所有員工到達之后,計數器為0,主線程才會繼續執行。
但子線程執行了countDown()方法,之后會繼續自己的工作,比如上面的【吃飯、喝水、拍照】,是不受主線程是否阻塞、其它線程是否已經執行countDown()方法的影響的。
5、CountDownLatch與CyclicBarrier的對比可以看:
java多線程CyclicBarrier使用示例,讓線程起步走
補充:CountDownLatch踩過的坑
線上生產環境dubbo報線程池滿了,經過一天排查鎖定在開三個線程計算最后合并數據的步驟中。簡單描述下該步驟線程開三個 調用三個不同的方法 使用countdownlatch 計數器等待三個方法全部執行完成 合并數據。
但是由于其中一個方法調用第三方接口,接口返回異常導致轉換數據報錯。導致其中一個方法未正常完成。
舉例demo:
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
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
|
public static void main(String[] args) { ExecutorService executorService =Executors.newFixedThreadPool( 3 ); CountDownLatch cdl = new CountDownLatch( 3 ); executorService.execute( new Runnable() { @Override public void run() { /*try { function1(); } catch (Exception e) { //異常處理 e.printStackTrace(); } finally { cdl.countDown(); }*/ function1(); } }); executorService.execute( new Runnable() { @Override public void run() { function2(); cdl.countDown(); } }); executorService.execute( new Runnable() { @Override public void run() { function3(); cdl.countDown(); } }); try { cdl.await(); //cdl.await(20,TimeUnit.SECONDS); System.out.println( "三個執行線程結束" ); } catch (InterruptedException e) { e.printStackTrace(); System.out.println( "執行線程異常" ); } finally { executorService.shutdown(); System.out.println( "執行線程關閉" ); } } private static void function1(){ int i = 10 / 0 ; System.out.println( "方法一" ); } private static void function2(){ System.out.println( "方法二" ); } private static void function3(){ System.out.println( "方法三" ); } |
方法一拋出異常,但是沒有做異常處理導致不會執行線程關閉步驟,是不是和想象中不一樣,一開始我也是懵,看了一下CountDownLatch原理就很好理解了,
“CountDownLatch是通過一個計數器來實現的,計數器的初始化值為線程的數量。每當一個線程完成了自己的任務后,計數器的值就相應得減1。當計數器到達0時,表示所有的線程都已完成任務,然后在閉鎖上等待的線程就可以恢復執行任務。”【1】
舉一個現實中例子就是:CountDownLatch 就像跑步比賽中的裁判,三個方法就是就是三位運動員,運動員2,3都已經到達終點,但是運動員1摔倒了,動不了。裁判員只看到兩位運動員到達終點不能宣布比賽結束,所以一直等。。。
就像這樣的場景導致線上service執行線程阻塞,接口調用次數累計導致dubbo線程滿了(跟dubbo線程模型有關,有時間具體談談這一點)
知道原因了,就要考慮怎么修改
比賽不能無限期等,所以比賽必須在有限時間內結束,所以使用
1
2
3
4
|
public boolean await( long timeout, TimeUnit unit) throws InterruptedException { return sync.tryAcquireSharedNanos( 1 , unit.toNanos(timeout)); } |
線程內部也許要增加異常處理
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
|
executorService.execute( new Runnable() { @Override public void run() { try { function1(); } catch (Exception e) { //異常處理 e.printStackTrace(); } finally { cdl.countDown(); } // function1(); } }); |
修改后demo
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
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
|
public static void main(String[] args) { ExecutorService executorService =Executors.newFixedThreadPool( 3 ); CountDownLatch cdl = new CountDownLatch( 3 ); executorService.execute( new Runnable() { @Override public void run() { try { function1(); } catch (Exception e) { //異常處理 e.printStackTrace(); } finally { cdl.countDown(); } // function1(); } }); executorService.execute( new Runnable() { @Override public void run() { function2(); cdl.countDown(); } }); executorService.execute( new Runnable() { @Override public void run() { function3(); cdl.countDown(); } }); try { // cdl.await(); cdl.await( 20 ,TimeUnit.SECONDS); System.out.println( "三個執行線程結束" ); } catch (InterruptedException e) { e.printStackTrace(); System.out.println( "執行線程異常" ); } finally { executorService.shutdown(); System.out.println( "執行線程關閉" ); } } private static void function1(){ int i = 10 / 0 ; System.out.println( "方法一" ); } private static void function2(){ System.out.println( "方法二" ); } private static void function3(){ System.out.println( "方法三" ); } |
執行結果
大家結合自己的現實使用修改,爬過了使用坑,記錄下分享下 ,希望能對別人有用
以上為個人經驗,希望能給大家一個參考,也希望大家多多支持服務器之家。如有錯誤或未考慮完全的地方,望不吝賜教。
原文鏈接:https://blog.csdn.net/javaloveiphone/article/details/54729821