java中的 CountDownLatch

實現原理:java

  • 今天瀏覽了一下它的源碼,發現其實現是十分簡單的,
  • 只是簡單的繼承了AbstractQueuedSynchronizer(AQS同步器),便實現了其功能。
  • 實現原理:
    • 讓須要的暫時阻塞的線程,進入一個死循環裏面,
    • 獲得某個條件後再退出循環,以此實現阻塞當前線程的效果。
    • setState咱們能夠暫時理解爲設置一個計數器,當前計數器初始值爲5。
      • 每次減一知道爲零跳出去

===================================================併發

一、在java.util.concurrent包下工具

  • 在java1.5被引入的
  • 一塊兒引入的併發工具類CyclicBarrier、Semaphore、ConcurrentHashMap和BlockingQueue

二、CountDownLatch 使一個線程等其餘線程完成各自的工做後在執行線程

三、CountDownLatch是經過一個計數器來實現的,計數器的初始值爲線程的數量code

  • 構造器中的計數值(count)實際上就是閉鎖須要等待的線程數量
  • 沒有提供任何機制去從新設置這個計數值

四、主線程必須在啓動其餘線程後當即調用CountDownLatch.await()方法對象

  • 其餘N 個線程必須引用閉鎖對象
  • 通知機制是經過 CountDownLatch.countDown()方法來完成
  • count的值等於0時,主線程就能經過await()方法,恢復執行本身的任務
public class Test {
     public static void main(String[] args) {   
         final CountDownLatch latch = new CountDownLatch(2);
 
         new Thread(){
             public void run() {
                 try {
                     System.out.println("子線程"+Thread.currentThread().getName()+"正在執行");
                    Thread.sleep(3000);
                    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(3000);
                     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();
        }
     }
}
相關文章
相關標籤/搜索