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

其中構造方法:
CountDownLatch(int count) 參數(shù)count是計數(shù)器,一般用要執(zhí)行線程的數(shù)量來賦值。
long getCount():獲得當前計數(shù)器的值。
void countDown():當計數(shù)器的值大于零時,調用方法,計數(shù)器的數(shù)值減少1,當計數(shù)器等數(shù)零時,釋放所有的線程。
void await():調所該方法阻塞當前主線程,直到計數(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
以上就是本文的全部內容,希望本文的內容對大家的學習或者工作能帶來一定的幫助,同時也希望多多支持腳本之家!
- java多線程CountDownLatch與線程池ThreadPoolExecutor/ExecutorService案例
- Java countDownLatch如何實現(xiàn)多線程任務阻塞等待
- 如何使用CountDownLatch同步java多線程
- java使用CountDownLatch等待多線程全部執(zhí)行完成
- JAVA多線程CountDownLatch使用詳解
- Java中CountDownLatch進行多線程同步詳解及實例代碼
- 詳解Java多線程編程中CountDownLatch阻塞線程的方法
- Java多線程編程之CountDownLatch同步工具使用實例
- Java多線程之同步工具類CountDownLatch
相關文章
關于解決iReport4.1.1無法正常啟動或者閃退或者JDK8不兼容的問題
在安裝使用iReport的過程中遇到一個問題,我的iReport始終不能打開,困擾了我好久。接下來通過本文給大家介紹iReport4.1.1無法正常啟動或者閃退或者JDK8不兼容的問題,需要的朋友可以參考下2018-09-09

