ContDownLatch是一個同步輔助類,在完成某些運算時,只有其餘全部線程的運算所有完成,當前運算才繼續執行,這就叫閉鎖ide
public class TestCountDownLatch { public static void main(String[] args){ LatchDemo ld = new LatchDemo(); long start = System.currentTimeMillis(); for (int i = 0;i<10;i++){ new Thread(ld).start(); } long end = System.currentTimeMillis(); System.out.println("耗費時間爲:"+(end - start)+"秒"); } } class LatchDemo implements Runnable{ private CountDownLatch latch; public LatchDemo(){ } @Override public void run() { for (int i = 0;i<5000;i++){ if (i % 2 == 0){//50000之內的偶數 System.out.println(i); } } } }
public class TestCountDownLatch { public static void main(String[] args) { final CountDownLatch latch = new CountDownLatch(10);//有多少個線程這個參數就是幾 LatchDemo ld = new LatchDemo(latch); long start = System.currentTimeMillis(); for (int i = 0; i < 10; i++) { new Thread(ld).start(); } try { latch.await();//這10個線程執行完以前先等待 } catch (InterruptedException e) { } long end = System.currentTimeMillis(); System.out.println("耗費時間爲:" + (end - start)); } } class LatchDemo implements Runnable { private CountDownLatch latch; public LatchDemo(CountDownLatch latch) { this.latch = latch; } @Override public void run() { synchronized (this) { try { for (int i = 0; i < 50000; i++) { if (i % 2 == 0) {//50000之內的偶數 System.out.println(i); } } } finally { latch.countDown();//每執行完一個就遞減一個 } } } }
如上代碼,主要就是用latch.countDown()
和latch.await()
實現閉鎖,詳細請看上面註釋便可。this