JAVA高级(7)—— 并发CountDownLatch

2018-01-01  本文已影响7人  AndroidMaster

一、是什么

CountDownLatch是一个java.util.concurrent包下的同步工具类,它允许一个或多个线程一直等待,直到其他线程的操作执行完后,然后在闭锁上等待的线程就可以恢复执行任务。例如,应用程序的主线程希望在负责启动框架服务的线程已经启动所有的框架服务之后再执行。
CountDownLatch的伪代码如下所示:

//Main thread start
//Create CountDownLatch for N threads
//Create and start N threads
//Main thread wait on latch
//N threads completes there tasks are returns
//Main thread resume execution

二、如何工作

构造函数:public void CountDownLatch(int count)

构造器中的计数值(count)实际上就是闭锁需要等待的线程数量。这个值只能被设置一次,没有提供任何机制去重新设置这个计数值。主线程必须在启动其他线程后立即调用await()方法。这样主线程的操作就会在这个方法上阻塞,直到其他线程完成各自的任务。其他N 个线程必须引用闭锁对象,因为他们需要通知CountDownLatch对象,他们已经完成了各自的任务。通过 countDown()方法来完成的;每调用一次这个方法,在构造函数中初始化的count值就减1。所以当N个线程都调 用了这个方法,count的值等于0,然后主线程就能通过await()方法,恢复执行自己的任务。

三、例子

在这个例子中,我模拟了一个应用程序启动类,它开始时启动了n个线程类,这些线程将检查外部系统并通知闭锁,并且启动类一直在闭锁上等待着。一旦验证和检查了所有外部服务,那么启动类恢复执行。

BaseHealthChecker.java:这个类是一个Runnable,负责所有特定的外部服务健康的检测。

public abstract class BaseHealthChecker implements Runnable {
    private CountDownLatch latch;
    private String serviceName;
    private boolean isReady;

    // Get latch object in constructor so that after completing the task, thread
    // can countDown() the latch
    public BaseHealthChecker(String serviceName, CountDownLatch latch) {
        this.latch = latch;
        this.serviceName = serviceName;
        this.isReady = false;
    }

    public void run() {
        try {
            verifyService();
            isReady = true;
        } catch (Throwable t) {
            t.printStackTrace(System.err);
            isReady = false;
        } finally {
            if (latch != null) {
                latch.countDown();
            }
        }
    }

    public String getServiceName() {
        return serviceName;
    }

    public boolean isReady() {
        return isReady;
    }

    // This method needs to be implemented by all specific service checker
    public abstract void verifyService();
}
public class NetworkHealthChecker extends BaseHealthChecker {

    public NetworkHealthChecker(CountDownLatch latch) {
        super("Network Service", latch);
    }

    @Override
    public void verifyService() {
        System.out.println("Checking " + this.getServiceName());
        try {
            Thread.sleep(7000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println(this.getServiceName() + " is READY");
    }
}
    public CacheHealthChecker(CountDownLatch latch) {
        super("Cache Service", latch);
    }

    @Override
    public void verifyService() {
        System.out.println("Checking " + this.getServiceName());
        try {
            Thread.sleep(7000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println(this.getServiceName() + " is READY");
    }

ApplicationStartupUtil:这个类是一个主启动类,它负责初始化闭锁,然后等待,直到所有服务都被检测完。

public class ApplicationStartupUtil {
    // List of service checkers
    private static List<BaseHealthChecker> services;

    // This latch will be used to wait on
    private static CountDownLatch latch;

    private ApplicationStartupUtil() {
    }

    private final static ApplicationStartupUtil INSTANCE = new ApplicationStartupUtil();

    public static ApplicationStartupUtil getInstance() {
        return INSTANCE;
    }

    public static boolean checkExternalServices() throws Exception {
        // Initialize the latch with number of service checkers
        latch = new CountDownLatch(3);

        // All add checker in lists
        services = new ArrayList<BaseHealthChecker>();
        services.add(new NetworkHealthChecker(latch));
        services.add(new CacheHealthChecker(latch));
        services.add(new DatabaseHealthChecker(latch));

        // Start service checkers using executor framework
        Executor executor = Executors.newFixedThreadPool(services.size());

        for (final BaseHealthChecker v : services) {
            executor.execute(v);
        }

        // Now wait till all services are checked
        latch.await();

        // Services are file and now proceed startup
        for (final BaseHealthChecker v : services) {
            if (!v.isReady()) {
                return false;
            }
        }
        return true;
    }
}
public class Main {
    public static void main(String[] args)
    {
        boolean result = false;
        try {
            result = ApplicationStartupUtil.checkExternalServices();
        } catch (Exception e) {
            e.printStackTrace();
        }
        System.out.println("External services validation completed !! Result was :: "+ result);
    }
}

输出:
Checking Network Service
Checking Cache Service
Cache Service is READY
Network Service is READY
External services validation completed !! Result was :: true

常见面试题

参考文献

什么时候使用CountDownLatch

上一篇 下一篇

猜你喜欢

热点阅读