Java中多線程同步類 CountDownLatch
在多線程開發(fā)中,常常遇到希望一組線程完成之后在執(zhí)行之后的操作,java提供了一個多線程同步輔助類,可以完成此類需求:
類中常見的方法:

其中構(gòu)造方法:
CountDownLatch(int count) 參數(shù)count是計數(shù)器,一般用要執(zhí)行線程的數(shù)量來賦值。
long getCount():獲得當(dāng)前計數(shù)器的值。
void countDown():當(dāng)計數(shù)器的值大于零時,調(diào)用方法,計數(shù)器的數(shù)值減少1,當(dāng)計數(shù)器等數(shù)零時,釋放所有的線程。
void await():調(diào)所該方法阻塞當(dāng)前主線程,直到計數(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();
}
}
}
輸出結(jié)果:
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)容對大家的學(xué)習(xí)或者工作能帶來一定的幫助,同時也希望多多支持腳本之家!
- java多線程CountDownLatch與線程池ThreadPoolExecutor/ExecutorService案例
- Java countDownLatch如何實現(xiàn)多線程任務(wù)阻塞等待
- 如何使用CountDownLatch同步j(luò)ava多線程
- java使用CountDownLatch等待多線程全部執(zhí)行完成
- JAVA多線程CountDownLatch使用詳解
- Java中CountDownLatch進(jìn)行多線程同步詳解及實例代碼
- 詳解Java多線程編程中CountDownLatch阻塞線程的方法
- Java多線程編程之CountDownLatch同步工具使用實例
- Java多線程之同步工具類CountDownLatch
相關(guān)文章
關(guān)于解決iReport4.1.1無法正常啟動或者閃退或者JDK8不兼容的問題
在安裝使用iReport的過程中遇到一個問題,我的iReport始終不能打開,困擾了我好久。接下來通過本文給大家介紹iReport4.1.1無法正常啟動或者閃退或者JDK8不兼容的問題,需要的朋友可以參考下2018-09-09
SpringBoot中controller深層詳細(xì)講解
這篇文章主要介紹了SpringBoot在Controller層接收參數(shù)的常用方法,本文通過實例代碼給大家介紹的非常詳細(xì),對大家的學(xué)習(xí)或工作具有一定的參考借鑒價值,需要的朋友可以參考下2023-02-02
淺談讓@Value更方便的Spring自定義轉(zhuǎn)換類
Spring為大家內(nèi)置了不少開箱即用的轉(zhuǎn)換類,如字符串轉(zhuǎn)數(shù)字、字符串轉(zhuǎn)時間等,但有時候需要使用自定義的屬性,則需要自定義轉(zhuǎn)換類了2021-06-06
如何基于Autowired對構(gòu)造函數(shù)進(jìn)行注釋
這篇文章主要介紹了如何基于Autowired對構(gòu)造函數(shù)進(jìn)行注釋,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友可以參考下2020-10-10

