【Coucurrency-CountDownLatch】-20161203-0002

簡介

java異步任務相關的工具。主要用在某些線程須要等到其餘線程完成某些操做後才能執行的場景。java

等待線程須要顯示的調用wait方法,表示線程當前掛起,須要等到countdownLatch到0才執行。另外一些線程調用countDown對countDownLatch - 1,達到0時則調用wait方法的線程獲得執行。dom

小故事

小明去吃鐵板燒快餐,來到窗口後他發現都是舊菜可是他但願吃剛煮好的。通過交談後師傅承諾以前的菜賣完就給他煮新的,這個時候小明就佔據了這個窗口,其餘窗口則繼續賣菜。終於舊菜賣完了小明也拿到了新的菜,愉快的吃起了飯。
這裏窗口就是線程數,小明所在窗口須要其餘窗口把舊菜賣完纔能有新的菜,小明所在的線程是掛起的,其餘窗口每賣一份就對這個菜減一。菜的量就是CountDownLatch。異步

DEMO

package calvin;

import java.util.Random;
import java.util.concurrent.CountDownLatch;

public class TestCountDownLatch {
    public static void main(String[] args){
        CountDownLatch latch = new CountDownLatch(2);
        Window win = null;
        for(int i =0; i< 4; i ++){
            win = new Window(latch);
            new Thread(win).start();
        }
        System.out.println("wait");
        try {
            latch.await();
        } catch (InterruptedException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        System.out.println("down");
    }
    
    public static class Window implements Runnable{
        private CountDownLatch latch = null;
        public Window(CountDownLatch latch){
            this.latch = latch;
        }
        
        @Override
        public void run(){
            int time = new Random().nextInt(5) * 1000;
            try {
                Thread.sleep(time);
            } catch (InterruptedException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            System.out.println("thread = " + Thread.currentThread().getName());
            latch.countDown();
        }
    }
}
// 運行結果:
wait
thread = Thread-1
thread = Thread-0
down
thread = Thread-3
thread = Thread-2

小結

CountDonwLatch能夠用做一個計數器。主要用在某個線程須要等待某個事件發生後才能被執行的地方。ide

本站公眾號
   歡迎關注本站公眾號,獲取更多信息