CountDownLatch,一個同步輔助類,在完成一組正在其他線程中執行的操作之前,它允許一個或多個線程一直等待。
主要方法
public CountDownLatch(int count);
public void countDown();
public void await() throws InterruptedException
構造方法參數指定了計數的次數
countDown方法,當前線程調用此方法,則計數減一
awaint方法,調用此方法會一直阻塞當前線程,直到計時器的值爲0
package multiThread; import java.util.concurrent.CountDownLatch; public class Demon3 { public static void main(String[] args) { CountDownLatch countDownLatch = new CountDownLatch(3); new MyThread(countDownLatch, "thread1").start(); new MyThread(countDownLatch, "thread2").start(); new MyThread(countDownLatch, "thread3").start(); try { //等待所有進程執行完 countDownLatch.await(); System.out.println("All thread stopped"); } catch (InterruptedException e) { e.printStackTrace(); } } } class MyThread extends Thread { private CountDownLatch countDownLatch; private String threadName; public MyThread(CountDownLatch countDownLatch, String threadName) { this.countDownLatch = countDownLatch; this.threadName = threadName; } @Override public void run() { System.out.println(threadName + "RUN!!"); try { Thread.sleep(10000); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println(threadName + "Stopped!!"); countDownLatch.countDown(); //執行完減1 } }