在多線程開發中,經常遇到但願一組線程完成以後在執行以後的操做,java提供了一個多線程同步輔助類,能夠完成此類需求:
類中常見的方法:
其中構造方法:CountDownLatch(int count) 參數count是計數器,通常用要執行線程的數量來賦值。
long getCount():得到當前計數器的值。
void countDown():當計數器的值大於零時,調用方法,計數器的數值減小1,當計數器等數零時,釋放全部的線程。
void await():調所該方法阻塞當前主線程,直到計數器減小爲零。
代碼例子:
線程類:java
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(); } } }
輸出結果:ide
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