1. CountDownLatch是什麼
是在 java1.5 被引入的,存在于
CountDownLatch
包下。
java.util.concurrent
這個類能夠使一個線程等待其他線程完成各自的工作後再執行。
CountDownLatch
CountDownLatch是通過一個計數器來實作的,計數器的初始值為線程的數量。每當一個線程完成了自己的任務後,計數器的值就會減1。當計數器值到達0時,它表示所有的線程已經完成了任務,然後在閉鎖上等待的線程就可以恢複執行任務。
CountDownLatch 通過一個給定的 count 數來被初始化, 其中await()方法會一直阻塞,直到目前的 count 被減到0,count 的遞減可以通過調用 countDown() 方法來實作的;在 await() 方法不再阻塞以後,所有正在等待的線程都會開始執行;
import java.util.concurrent.CountDownLatch;
public class CountDownLatchDemo {
public static void main(String[] args) {
final CountDownLatch latch = new CountDownLatch();
new Thread() {
public void run() {
try {
System.out.println("子線程" + Thread.currentThread().getName() + "正在執行");
Thread.sleep();
System.out.println("子線程" + Thread.currentThread().getName() + "執行完畢");
latch.countDown();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}.start();
new Thread() {
public void run() {
try {
System.out.println("子線程" + Thread.currentThread().getName() + "正在執行");
Thread.sleep();
System.out.println("子線程" + Thread.currentThread().getName() + "執行完畢");
latch.countDown();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}.start();
try {
System.out.println("等待2個子線程執行完畢...");
latch.await();
System.out.println("2個子線程已經執行完畢");
System.out.println("繼續執行主線程");
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
參考文章:http://www.importnew.com/15731.html