溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊(cè)×
其他方式登錄
點(diǎn)擊 登錄注冊(cè) 即表示同意《億速云用戶服務(wù)條款》

Java中多線程同步類(lèi) CountDownLatch

發(fā)布時(shí)間:2020-10-17 00:36:33 來(lái)源:腳本之家 閱讀:145 作者:行者無(wú)疆-ITer 欄目:編程語(yǔ)言

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

類(lèi)中常見(jiàn)的方法:

Java中多線程同步類(lèi) CountDownLatch

其中構(gòu)造方法:

CountDownLatch(int count) 參數(shù)count是計(jì)數(shù)器,一般用要執(zhí)行線程的數(shù)量來(lái)賦值。

long getCount():獲得當(dāng)前計(jì)數(shù)器的值。

void countDown():當(dāng)計(jì)數(shù)器的值大于零時(shí),調(diào)用方法,計(jì)數(shù)器的數(shù)值減少1,當(dāng)計(jì)數(shù)器等數(shù)零時(shí),釋放所有的線程。

void await():調(diào)所該方法阻塞當(dāng)前主線程,直到計(jì)數(shù)器減少為零。

代碼例子:

線程類(lèi):

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();//告訴同步類(lèi)完成一個(gè)線程操作完成

}
private void dowork(){
 try {
 Thread.sleep(2000);
 System.out.println(threadName+" is working...");
 } catch (InterruptedException e) {
 // TODO Auto-generated catch block
 e.printStackTrace();
 }

}

}

測(cè)試類(lèi):

import java.util.concurrent.CountDownLatch;
public class TsetCountDownLatch {

 public static void main(String[] args) {
 try {
  CountDownLatch cd = new CountDownLatch(3);// 表示一共有三個(gè)線程
  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

以上就是本文的全部?jī)?nèi)容,希望本文的內(nèi)容對(duì)大家的學(xué)習(xí)或者工作能帶來(lái)一定的幫助,同時(shí)也希望多多支持億速云!

向AI問(wèn)一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI