CountDownLatch的使用

參考自博客:https://zapldy.iteye.com/blog/746458,感受很好,簡單易懂。java

舉個例子,有三個工人在爲老闆幹活,這個老闆有一個習慣,就是當三個工人把一天的活都幹完了的時候,他就來檢查全部工人所幹的活。記住這個條件:三個工人先所有幹完活,老闆才檢查。因此在這裏用Java代碼設計兩個類,Worker表明工人,Boss表明老闆,具體的代碼實現以下:dom

Worker:ide

package com.cy.model;


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

public class Worker implements Runnable {
    private CountDownLatch latch;
    private String name;

    public Worker(CountDownLatch latch, String name) {
        this.latch = latch;
        this.name = name;
    }

    @Override
    public void run() {
        this.doWork();

        try {
            TimeUnit.SECONDS.sleep(new Random().nextInt(10));
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println(this.name + "活幹完了!");

        this.latch.countDown();
    }

    private void doWork(){
        System.out.println(this.name + "正在幹活!");
    }
}

Boss:測試

package com.cy.model;

import java.util.concurrent.CountDownLatch;

public class Boss implements Runnable{
    private CountDownLatch latch;

    public Boss(CountDownLatch latch) {
        this.latch = latch;
    }

    @Override
    public void run() {
        System.out.println("老闆正在等全部的工人幹完活......");

        try {
            this.latch.await();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        System.out.println("工人活都幹完了,老闆開始檢查了!");
    }
}

測試程序:this

package com.cy.test.thread;

import com.cy.model.Boss;
import com.cy.model.Worker;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class CountDownLatchDemo {

    public static void main(String[] args) {
        ExecutorService executor = Executors.newCachedThreadPool();

        CountDownLatch latch = new CountDownLatch(3);
        Worker w1 = new Worker(latch,"張三");
        Worker w2 = new Worker(latch,"李四");
        Worker w3 = new Worker(latch,"王五");

        Boss boss = new Boss(latch);

        executor.execute(w1);
        executor.execute(w2);
        executor.execute(w3);
        executor.execute(boss);

        executor.shutdown();
    }

}

運行結果:spa

張三正在幹活!
王五正在幹活!
李四正在幹活!
老闆正在等全部的工人幹完活......
張三活幹完了!
李四活幹完了!
王五活幹完了!
工人活都幹完了,老闆開始檢查了!

當你運行CountDownLatchDemo這個對象的時候,你會發現是等全部的工人都幹完了活,老闆纔來檢查,下面是我本地機器上運行的一次結果,能夠確定的每次運行的結果可能與下面不同,但老闆檢查永遠是在後面的。設計

相關文章
相關標籤/搜索