欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

Java中多線程同步類 CountDownLatch

 更新時間:2017年05月02日 10:22:07   作者:行者無疆-ITer  
本篇文章主要介紹了Java中多線程同步類 CountDownLatch的相關知識,具有很好的參考價值。下面跟著小編一起來看下吧

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

類中常見的方法:

其中構造方法:

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

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

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

void await():調(diào)所該方法阻塞當前主線程,直到計數(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

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

相關文章

最新評論