CountDownLatch的使用

参考自博客:https://zapldy.iteye.com/blog/746458,感觉很好,简单易懂。

举个例子,有三个工人在为老板干活,这个老板有一个习惯,就是当三个工人把一天的活都干完了的时候,他就来检查所有工人所干的活。记住这个条件:三个工人先全部干完活,老板才检查。所以在这里用Java代码设计两个类,Worker代表工人,Boss代表老板,具体的代码实现如下:

Worker:

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("工人活都干完了,老板开始检查了!");
    }
}

测试程序:

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();
    }

}

运行结果:

张三正在干活!
王五正在干活!
李四正在干活!
老板正在等所有的工人干完活......
张三活干完了!
李四活干完了!
王五活干完了!
工人活都干完了,老板开始检查了!

当你运行CountDownLatchDemo这个对象的时候,你会发现是等所有的工人都干完了活,老板才来检查,下面是我本地机器上运行的一次结果,可以肯定的每次运行的结果可能与下面不一样,但老板检查永远是在后面的。

 

上一篇:java常用关键字(CyclicBarrier,CountDownLatch)


下一篇:java多线程笔记