Java中多線程同步類 CountDownLatch
在多線程開發(fā)中,常常遇到希望一組線程完成之后在執(zhí)行之后的操作,java提供了一個多線程同步輔助類,可以完成此類需求:
類中常見的方法:
其中構造方法:
CountDownLatch(int count) 參數(shù)count是計數(shù)器,一般用要執(zhí)行線程的數(shù)量來賦值。
long getCount():獲得當前計數(shù)器的值。
void countDown():當計數(shù)器的值大于零時,調(diào)用方法,計數(shù)器的數(shù)值減少1,當計數(shù)器等數(shù)零時,釋放所有的線程。
void await():調(diào)所該方法阻塞當前主線程,直到計數(shù)器減少為零。
代碼例子:
線程類:
import java.util.concurrent.CountDownLatch; public class TestThread extends Thread{ CountDownLatch cd; String threadName; public TestThread(CountDownLatch cd,String threadName){ this.cd=cd; this.threadName=threadName; } @Override public void run() { System.out.println(threadName+" start working..."); dowork(); System.out.println(threadName+" end working and exit..."); cd.countDown();//告訴同步類完成一個線程操作完成 } private void dowork(){ try { Thread.sleep(2000); System.out.println(threadName+" is working..."); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }
測試類:
import java.util.concurrent.CountDownLatch; public class TsetCountDownLatch { public static void main(String[] args) { try { CountDownLatch cd = new CountDownLatch(3);// 表示一共有三個線程 TestThread thread1 = new TestThread(cd, "thread1"); TestThread thread2 = new TestThread(cd, "thread2"); TestThread thread3 = new TestThread(cd, "thread3"); thread1.start(); thread2.start(); thread3.start(); cd.await();//等待所有線程完成 System.out.println("All Thread finishd"); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }
輸出結果:
thread1 start working... thread2 start working... thread3 start working... thread2 is working... thread2 end working and exit... thread1 is working... thread3 is working... thread3 end working and exit... thread1 end working and exit... All Thread finishd
以上就是本文的全部內(nèi)容,希望本文的內(nèi)容對大家的學習或者工作能帶來一定的幫助,同時也希望多多支持腳本之家!
- java多線程CountDownLatch與線程池ThreadPoolExecutor/ExecutorService案例
- Java countDownLatch如何實現(xiàn)多線程任務阻塞等待
- 如何使用CountDownLatch同步java多線程
- java使用CountDownLatch等待多線程全部執(zhí)行完成
- JAVA多線程CountDownLatch使用詳解
- Java中CountDownLatch進行多線程同步詳解及實例代碼
- 詳解Java多線程編程中CountDownLatch阻塞線程的方法
- Java多線程編程之CountDownLatch同步工具使用實例
- Java多線程之同步工具類CountDownLatch
相關文章
淺析如何在SpringBoot中實現(xiàn)數(shù)據(jù)脫敏
脫敏是指在不改變原數(shù)據(jù)結構的前提下,通過某種方式處理數(shù)據(jù),使數(shù)據(jù)不能直接暴露用戶的真實信息,下面我們就來看看SpringBoot中實現(xiàn)數(shù)據(jù)脫敏的具體方法吧2024-03-03SpringBoot FailureAnalyzer實例使用教程
FailureAnalyzer是一種在啟動時攔截exception并將其轉換為human-readable消息的好方法,包含在故障分析中。SpringBoot為application context相關的exceptions,JSR-303驗證等提供了這樣的分析器,實際上很容易創(chuàng)建自己的2022-12-12Java concurrency之公平鎖(二)_動力節(jié)點Java學院整理
這篇文章主要為大家詳細介紹了Java concurrency之公平鎖的第二篇內(nèi)容,具有一定的參考價值,感興趣的小伙伴們可以參考一下2017-06-06Java中的InputStreamReader和OutputStreamWriter源碼分析_動力節(jié)點Java學院整理
本文通過示例代碼給大家解析了Java中的InputStreamReader和OutputStreamWriter知識,需要的的朋友參考下吧2017-05-05jsp、struts、spring、mybatis實現(xiàn)前端頁面功能模塊化拆分的方案
這篇文章主要介紹了 jsp、struts、spring、mybatis實現(xiàn)前端頁面功能模塊化拆分的方案,非常不錯,需要的朋友參考下2017-01-01