Java執行緒--CountDownLatch倒計數器
CountDownLatch倒計數器
目錄
CountDownLatch場景
想要做當前事情之前,必須具備前期的若干事件都準備完畢,當前事件才能進行。用程式來說,就是:
當前執行緒處於阻塞狀態,必須等到其它的若干執行緒都執行完畢之後,當前執行緒才被喚醒得以執行。
CountDownLatch原理
CountDownLatch類的原始碼:內部私有類Sync繼承AQS,最主要的兩個方法await()、countDown()。CountDownLatch類是共享模式的同步器。至於AQS,concurrent包的基石,建議參考
CountDownLatch類其實是實現了執行緒之間的通訊,其背後實現的本質是利用了Object物件的wait()、notify()、notifyAll()方法來達到執行緒之間的通訊。
await()方法,功能類似Object的wait()方法,進行當前執行緒的阻塞。
countDown()方法,其內部邏輯是計數遞減1,然後判斷計數是否為零。直到計數當前為零,才喚醒阻塞的執行緒。功能類似Object的notify()、notifyAll()方法
CountDownLatch示例
import java.util.concurrent.*; import java.util.concurrent.locks.*; import java.util.concurrent.atomic.*; class PrepareEvent implements Runnable { private CountDownLatch c ; public PrepareEvent(CountDownLatch c){ this.c = c ; } public void run(){ try{ long time = (long)(Math.random() * 5000); //模擬前期準備事件耗時 Thread.sleep(time); String tName = Thread.currentThread().getName(); System.out.println(tName+"' working time is: "+time); }catch(InterruptedException e){} c.countDown(); } } public class CountDownLatchTest { public static void main(String[] args) { int count = 5 ;//計數5 CountDownLatch c = new CountDownLatch(count); Thread[] ts = new Thread[count]; System.out.println("CountDownLatch init, now count is: "+c.getCount()+"\n\r"); System.out.println("because Of await(), main blocking...\n\r"); for(int i=count-1; i>=0; i--){ ts[i] = new Thread(new PrepareEvent(c),"T"+i); ts[i].start(); } try{ c.await();//這裡阻塞,直至計數降為零 }catch(InterruptedException e){} System.out.println(" \n\rafter await(), main continue...\n\r"); System.out.println("CountDownLatch used, now count is: "+c.getCount()+"\n\r"); } }
執行結果如下:
CountDownLatch init, now count is: 5
because Of await(), main blocking...
T3' working time is: 1099
T2' working time is: 3320
T0' working time is: 3448
T4' working time is: 3647
T1' working time is: 3825
after await(), main continue...
CountDownLatch used, now count is: 0