java.util.concurrent包下同步輔助工具類CountDownLatch
阿新 • • 發佈:2018-12-31
CountDownLatch作為一個輔助工具類,它允許一個或多個執行緒等待一系列指定操作的完成。CountDownLatch以一個給定值進行初始化,通過CountDownLatch cdl = new CountDownLatch(n); 通過cdl.await()方法進行阻塞,並等待計數器的值被減到0,其他執行緒每呼叫一次cdl.countDown方法,該計數器的值就會-1,等待計數器的初始值n減到0時,之前阻塞執行緒就會被自動喚醒,繼續執行。
具體事例程式碼如下:
package com.zn.senior.queue; import java.util.concurrent.CountDownLatch; public class CountDownLatchDemo { public static void main(String[] args) { CountDownLatch cdl = new CountDownLatch(3); new Thread(new Runnable() { @Override public void run() { // TODO Auto-generated method stub System.out.println("等待CountDownLatch計數器值減到0"); try { cdl.await(); //等待CountDownLatch計數器值減到0 System.out.println("執行緒被喚醒"); //當CountDownLatch計數器為0時,該執行緒會被喚醒,繼續向下執行。 } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }).start(); new Thread(new Runnable() { @Override public void run() { // TODO Auto-generated method stub while(cdl.getCount()>0){ cdl.countDown(); System.out.println("CountDownLatch計數器值-1"); try { Thread.sleep(1000); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } }).start(); } }