java多線程CountDownLatch與線程池ThreadPoolExecutor/ExecutorService案例
一個(gè)同步工具類,它允許一個(gè)或多個(gè)線程一直等待,直到其他線程的操作執(zhí)行完后再執(zhí)行。
2、ThreadPoolExecutor/ExecutorService:線程池,使用線程池可以復(fù)用線程,降低頻繁創(chuàng)建線程造成的性能消耗,同時(shí)對(duì)線程的創(chuàng)建、啟動(dòng)、停止、銷毀等操作更簡(jiǎn)便。
3、使用場(chǎng)景舉例:年末公司組織團(tuán)建,要求每一位員工周六上午8點(diǎn)到公司門口集合,統(tǒng)一乘坐公司所租大巴前往目的地。
在這個(gè)案例中,公司作為主線程,員工作為子線程。
4、代碼示例: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 創(chuàng)建時(shí)間:2017年1月25日 上午10:59:11 * @Description: */public class Company { public static void main(String[] args) throws InterruptedException { //員工數(shù)量 int count = 5; //創(chuàng)建計(jì)數(shù)器 //構(gòu)造參數(shù)傳入的數(shù)量值代表的是latch.countDown()調(diào)用的次數(shù) CountDownLatch latch = new CountDownLatch(count); //創(chuàng)建線程池,可以通過(guò)以下方式創(chuàng)建 //ThreadPoolExecutor threadPool = new ThreadPoolExecutor(1,1,60,TimeUnit.SECONDS,new LinkedBlockingQueue<Runnable>(count)); ExecutorService threadPool = Executors.newFixedThreadPool(count); System.out.println('公司發(fā)送通知,每一位員工在周六早上8點(diǎn)到公司大門口集合'); for(int i =0;i<count ;i++){ //將子線程添加進(jìn)線程池執(zhí)行 Thread.sleep(10); threadPool.execute(new Employee(latch,i+1)); } try { //阻塞當(dāng)前線程,直到所有員工到達(dá)公司大門口之后才執(zhí)行 latch.await(); // 使當(dāng)前線程在鎖存器倒計(jì)數(shù)至零之前一直等待,除非線程被中斷或超出了指定的等待時(shí)間。 //latch.await(long timeout, TimeUnit unit) System.out.println('所有員工已經(jīng)到達(dá)公司大門口,大巴車發(fā)動(dòng),前往活動(dòng)目的地。'); } catch (InterruptedException e) { e.printStackTrace(); }finally{ //最后關(guān)閉線程池,但執(zhí)行以前提交的任務(wù),不接受新任務(wù) threadPool.shutdown(); //關(guān)閉線程池,停止所有正在執(zhí)行的活動(dòng)任務(wù),暫停處理正在等待的任務(wù),并返回等待執(zhí)行的任務(wù)列表。 //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+',已到達(dá)。'); } catch (Exception e) { e.printStackTrace(); }finally{ //當(dāng)前計(jì)算工作已結(jié)束,計(jì)數(shù)器減一 latch.countDown(); try { Thread.sleep(10); } catch (InterruptedException e) { e.printStackTrace(); } //執(zhí)行coutDown()之后,繼續(xù)執(zhí)行自己的工作,不受主線程的影響 System.out.println('員工:'+employeeIndex+',吃飯、喝水、拍照。'); } }}
打印輸出結(jié)果如下:
公司發(fā)送通知,每一位員工在周六早上8點(diǎn)到公司大門口集合員工:1,正在前往公司大門口集合...員工:1,已到達(dá)。員工:2,正在前往公司大門口集合...員工:2,已到達(dá)。員工:1,吃飯、喝水、拍照。員工:3,正在前往公司大門口集合...員工:2,吃飯、喝水、拍照。員工:3,已到達(dá)。員工:4,正在前往公司大門口集合...員工:3,吃飯、喝水、拍照。員工:4,已到達(dá)。員工:5,正在前往公司大門口集合...員工:4,吃飯、喝水、拍照。員工:5,已到達(dá)。所有員工已經(jīng)到達(dá)公司大門口,大巴車發(fā)動(dòng),前往活動(dòng)目的地。員工:5,吃飯、喝水、拍照。注意:
每一個(gè)員工到達(dá)之后,執(zhí)行countDown()方法,直到所有員工到達(dá)之后,計(jì)數(shù)器為0,主線程才會(huì)繼續(xù)執(zhí)行。
但子線程執(zhí)行了countDown()方法,之后會(huì)繼續(xù)自己的工作,比如上面的【吃飯、喝水、拍照】,是不受主線程是否阻塞、其它線程是否已經(jīng)執(zhí)行countDown()方法的影響的。
5、CountDownLatch與CyclicBarrier的對(duì)比可以看:java多線程CyclicBarrier使用示例,讓線程起步走
補(bǔ)充:CountDownLatch踩過(guò)的坑
線上生產(chǎn)環(huán)境dubbo報(bào)線程池滿了,經(jīng)過(guò)一天排查鎖定在開三個(gè)線程計(jì)算最后合并數(shù)據(jù)的步驟中。簡(jiǎn)單描述下該步驟線程開三個(gè) 調(diào)用三個(gè)不同的方法 使用countdownlatch 計(jì)數(shù)器等待三個(gè)方法全部執(zhí)行完成 合并數(shù)據(jù)。
但是由于其中一個(gè)方法調(diào)用第三方接口,接口返回異常導(dǎo)致轉(zhuǎn)換數(shù)據(jù)報(bào)錯(cuò)。導(dǎo)致其中一個(gè)方法未正常完成。
舉例demo:
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('三個(gè)執(zhí)行線程結(jié)束'); } catch (InterruptedException e) { e.printStackTrace(); System.out.println('執(zhí)行線程異常'); } finally { executorService.shutdown(); System.out.println('執(zhí)行線程關(guān)閉'); }}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('方法三');}
方法一拋出異常,但是沒有做異常處理導(dǎo)致不會(huì)執(zhí)行線程關(guān)閉步驟,是不是和想象中不一樣,一開始我也是懵,看了一下CountDownLatch原理就很好理解了,
“CountDownLatch是通過(guò)一個(gè)計(jì)數(shù)器來(lái)實(shí)現(xiàn)的,計(jì)數(shù)器的初始化值為線程的數(shù)量。每當(dāng)一個(gè)線程完成了自己的任務(wù)后,計(jì)數(shù)器的值就相應(yīng)得減1。當(dāng)計(jì)數(shù)器到達(dá)0時(shí),表示所有的線程都已完成任務(wù),然后在閉鎖上等待的線程就可以恢復(fù)執(zhí)行任務(wù)。”【1】
舉一個(gè)現(xiàn)實(shí)中例子就是:CountDownLatch 就像跑步比賽中的裁判,三個(gè)方法就是就是三位運(yùn)動(dòng)員,運(yùn)動(dòng)員2,3都已經(jīng)到達(dá)終點(diǎn),但是運(yùn)動(dòng)員1摔倒了,動(dòng)不了。裁判員只看到兩位運(yùn)動(dòng)員到達(dá)終點(diǎn)不能宣布比賽結(jié)束,所以一直等。。。
就像這樣的場(chǎng)景導(dǎo)致線上service執(zhí)行線程阻塞,接口調(diào)用次數(shù)累計(jì)導(dǎo)致dubbo線程滿了(跟dubbo線程模型有關(guān),有時(shí)間具體談?wù)勥@一點(diǎn))
知道原因了,就要考慮怎么修改比賽不能無(wú)限期等,所以比賽必須在有限時(shí)間內(nèi)結(jié)束,所以使用
public boolean await(long timeout, TimeUnit unit) throws InterruptedException { return sync.tryAcquireSharedNanos(1, unit.toNanos(timeout));}
線程內(nèi)部也許要增加異常處理
executorService.execute(new Runnable() { @Override public void run() { try { function1(); } catch (Exception e) { //異常處理 e.printStackTrace(); } finally { cdl.countDown(); } // function1(); }});修改后demo
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('三個(gè)執(zhí)行線程結(jié)束'); } catch (InterruptedException e) { e.printStackTrace(); System.out.println('執(zhí)行線程異常'); } finally { executorService.shutdown(); System.out.println('執(zhí)行線程關(guān)閉'); }}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('方法三');}
執(zhí)行結(jié)果
大家結(jié)合自己的現(xiàn)實(shí)使用修改,爬過(guò)了使用坑,記錄下分享下 ,希望能對(duì)別人有用
以上為個(gè)人經(jīng)驗(yàn),希望能給大家一個(gè)參考,也希望大家多多支持好吧啦網(wǎng)。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教。
相關(guān)文章:
1. 如何利用python操作注冊(cè)表2. 使用Hangfire+.NET 6實(shí)現(xiàn)定時(shí)任務(wù)管理(推薦)3. Xml簡(jiǎn)介_動(dòng)力節(jié)點(diǎn)Java學(xué)院整理4. jsp文件下載功能實(shí)現(xiàn)代碼5. 詳解瀏覽器的緩存機(jī)制6. ASP動(dòng)態(tài)網(wǎng)頁(yè)制作技術(shù)經(jīng)驗(yàn)分享7. xml中的空格之完全解說(shuō)8. 如何在jsp界面中插入圖片9. phpstudy apache開啟ssi使用詳解10. JSP之表單提交get和post的區(qū)別詳解及實(shí)例
