在多線程開發中,常常遇到希望一組線程完成之后在執行之后的操作,java提供了一個多線程同步輔助類,可以完成此類需求:
成都創新互聯專注為客戶提供全方位的互聯網綜合服務,包含不限于網站制作、成都網站設計、樂昌網絡推廣、微信小程序定制開發、樂昌網絡營銷、樂昌企業策劃、樂昌品牌公關、搜索引擎seo、人物專訪、企業宣傳片、企業代運營等,從售前售中售后,我們都將竭誠為您服務,您的肯定,是我們最大的嘉獎;成都創新互聯為所有大學生創業者提供樂昌建站搭建服務,24小時服務熱線:18982081108,官方網址:www.yijiale78.com
類中常見的方法:

其中構造方法:
CountDownLatch(int count) 參數count是計數器,一般用要執行線程的數量來賦值。
long getCount():獲得當前計數器的值。
void countDown():當計數器的值大于零時,調用方法,計數器的數值減少1,當計數器等數零時,釋放所有的線程。
void await():調所該方法阻塞當前主線程,直到計數器減少為零。
代碼例子:
線程類:
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
瀏覽地址:http://www.yijiale78.com/article38/pcpjsp.html
成都網站建設公司_創新互聯,為您提供靜態網站、ChatGPT、搜索引擎優化、面包屑導航、網站建設、定制網站
聲明:本網站發布的內容(圖片、視頻和文字)以用戶投稿、用戶轉載內容為主,如果涉及侵權請盡快告知,我們將會在第一時間刪除。文章觀點不代表本網站立場,如需處理請聯系客服。電話:028-86922220;郵箱:631063699@qq.com。內容未經允許不得轉載,或轉載時需注明來源: 創新互聯