一区二区三区在线-一区二区三区亚洲视频-一区二区三区亚洲-一区二区三区午夜-一区二区三区四区在线视频-一区二区三区四区在线免费观看

服務器之家:專注于服務器技術及軟件下載分享
分類導航

PHP教程|ASP.NET教程|Java教程|ASP教程|編程技術|正則表達式|C/C++|IOS|C#|Swift|Android|VB|R語言|JavaScript|易語言|vb.net|

服務器之家 - 編程語言 - Java教程 - Java中多線程同步類 CountDownLatch

Java中多線程同步類 CountDownLatch

2020-09-22 10:15行者無疆-ITer Java教程

本篇文章主要介紹了Java中多線程同步類 CountDownLatch的相關知識,具有很好的參考價值。下面跟著小編一起來看下吧

多線程開發中,常常遇到希望一組線程完成之后在執行之后的操作,java提供了一個多線程同步輔助類,可以完成此類需求:

類中常見的方法:

Java中多線程同步類 CountDownLatch

其中構造方法:

CountDownLatch(int count) 參數count是計數器,一般用要執行線程的數量來賦值。

long getCount():獲得當前計數器的值。

void countDown():當計數器的值大于零時,調用方法,計數器的數值減少1,當計數器等數零時,釋放所有的線程。

void await():調所該方法阻塞當前主線程,直到計數器減少為零。

代碼例子:

線程類:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
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();
 }
 
}
 
}

測試類:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
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();
 }
 }
}

輸出結果:

?
1
2
3
4
5
6
7
8
9
10
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

以上就是本文的全部內容,希望本文的內容對大家的學習或者工作能帶來一定的幫助,同時也希望多多支持服務器之家!

原文鏈接:http://www.cnblogs.com/ITer-jack/p/6791803.html

延伸 · 閱讀

精彩推薦
主站蜘蛛池模板: 色欲麻将 | 亚洲卡一卡2卡三卡4卡无卡三 | 亚洲欧美另类在线观看 | 日韩综合第一页 | 国产品精人成福利视频 | 超爽人人做人人爽 | 四虎影院2019 | 人人爱天天做夜夜爽88 | 精品高潮呻吟99AV无码 | 日本道高清 | 精品免费视在线观看 | 日b在线 | 欧美亚洲国产综合在线 | 日韩国产欧美视频 | 18性夜影院午夜寂寞影院免费 | 国产色网址 | 三上悠亚国产精品一区 | www红色一片在线观看版 | 亚飞与亚基国语1080p在线观看 | 色播开心网 | 国产日韩精品欧美一区 | 欧美日韩中文字幕久久伊人 | 99爱免费 | 日本免费不卡在线一区二区三区 | 女人扒开下面让男人桶爽视频 | 亚洲国产精品婷婷久久久久 | 视频一区 日韩 | 亚洲麻豆精品果冻传媒 | 青青热久免费精品视频精品 | 欧美三级一区二区 | 奶茶视频有容乃大 | 掀开奶罩边躁狠狠躁软学生 | 99热这里有免费国产精品 | 九九热免费在线观看 | 黑白配高清hd在线视频 | 俄罗斯一级淫片bbbb | 亚洲欧美日韩国产综合专区 | 天天插综合网 | 国产视频一区二 | 亚洲第五页 | 亚洲一区二区三区在线播放 |