CountDownLatch学习
看了几篇博客,说用CountDownLatch实现一个先执行完子线程,再执行主线程的例子。因此写一篇博客总结一下。
一、CountDownLatch了解
1.CountDownLatch继承了AbstractQueuedSynchronizer类,很多方法都封装了在这个类里面,感兴趣可以看一下。内部写了一个Sync类,对其进行各种操作,以完成各个功能。
2.其原理是实现了一个计数器,通过对计数器操作,来实现对各个子线程的监控
二、例子
1.在启动服务前,需要对各个组件进行健康检查,因此设计一个方案,对各个组件进行检查,环境都ok后,再执行主线程。
2.先定义一个抽象类,该类实现了Runnable,用来进行健康检查
public abstract class BaseHealthChecker implements Runnable {
//Counter
private CountDownLatch counter;
private String serviceName;
private boolean isServiceOk; public abstract void checkHealth(); public String getServiceName() {
return serviceName;
} public boolean isServiceOk() {
return isServiceOk;
} public BaseHealthChecker(String serviceName, CountDownLatch countDownLatch) {
this.counter = countDownLatch;
this.serviceName = serviceName;
this.isServiceOk = false;
} @Override
public void run() {
try {
checkHealth();
isServiceOk = true;
} catch (Throwable t) {
t.printStackTrace();
isServiceOk = false;
} finally {
//Always count down counter
if (counter != null) {
counter.countDown();
}
}
}
}
3.再定义一个HealthChecker.
package countdownlatch; import java.util.concurrent.CountDownLatch; /**
* Created by adrian.wu on 2018/12/18.
*/
public class HealthChecker extends BaseHealthChecker{
public HealthChecker(String serviceName, CountDownLatch counter){
super(serviceName, counter);
} @Override
public void checkHealth(){
System.out.println("Check " + this.getServiceName());
try {
Thread.sleep(7000);
}catch (InterruptedException e){
e.printStackTrace();
}
System.out.println(this.getServiceName() + " is Ok");
}
}
4.设定要检查哪些service
package countdownlatch; import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.Executor;
import java.util.concurrent.Executors; /**
* Created by adrian.wu on 2018/12/18.
*/
public class ApplicationStartupUtil {
private static List<BaseHealthChecker> services; 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 service checkers
latch = new CountDownLatch(4); services = new ArrayList<>(); services.add(new HealthChecker("Flink Cluster", latch)); services.add(new HealthChecker("Hbase Cluster", latch)); services.add(new HealthChecker("Spark Cluster", latch)); services.add(new HealthChecker("Kafka Cluster", latch)); Executor executor = Executors.newFixedThreadPool(services.size()); for (final BaseHealthChecker v : services) {
executor.execute(v);
} //wait all threads okay
latch.await(); for (final BaseHealthChecker v : services) {
if (!v.isServiceOk()) {
return false;
}
} return true;
}
}
5.检查服务
package countdownlatch; /**
* Created by adrian.wu on 2018/12/18.
*/
public class Check {
public static void main(String[] args) {
boolean result = false;
try {
result = ApplicationStartupUtil.checkExternalServices();
} catch (Exception e) {
e.printStackTrace();
}
System.out.println("Services check is ok. Result: " + result);
}
}
参考:http://www.importnew.com/15731.html
CountDownLatch学习的更多相关文章
- Java多线程之CountDownLatch学习
给出官网上的例子:http://docs.oracle.com/javase/7/docs/api/java/util/concurrent/CountDownLatch.html Java中conc ...
- JUC包下CountDownLatch学习笔记
CountDownLatch的作用是能使用多个线程进来之后,且线程任务执行完毕之后,才执行, 闭锁(Latch):一种同步方法,可以延迟线程的进度直到线程到达某个终点状态.通俗的讲就是,一个闭锁相当于 ...
- Gradle项目学习 & HttpAsyncClient学习 & CountDownLatch学习
装了Intellij,就是装了Gradle. 新建一个Gradle项目.然后下面这个页面要勾选上面两项: Use auto-import和Create directories for empty co ...
- 线程等待——CountDownLatch使用
告警性能优化过程中,遇到如下问题:1. 在数据库计算几十万个实体的KPI值的方差:2. 计算结果进行表格化处理. 这里KPI包含多个Counter的数据库函数运算(比如Decode,AVG等函数),方 ...
- Java CountDownLatch解析(下)
写在前面的话 在上一篇CountDownLatch解析中,我们了解了CountDownLatch的简介.CountDownLatch实用场景.CountDownLatch实现原理中的await()方法 ...
- 多个线程运行结束之后主线程再执行CountDownLatch
多个线程运行结束之后主线程再执行CountDownLatch 学习了:http://blog.csdn.net/lvyuanj/article/details/50737123 这个要膜拜一下! h ...
- Java核心知识点学习----多线程 倒计时记数器CountDownLatch和数据交换的Exchanger
本文将要介绍的内容都是Java5中的新特性,一个是倒计时记数器---CountDownLatch,另一个是用于线程间数据交换的Exchanger. 一.CountDownLatch 1.什么是Coun ...
- CountDownLatch的原理学习
转载:http://blog.csdn.net/yanyan19880509/article/details/52349056 前言 前面介绍了ReentrantLock,又叫排他锁,本篇主要通过Co ...
- 多线程学习笔记六之并发工具类CountDownLatch和CyclicBarrier
目录 简介 CountDownLatch 示例 实现分析 CountDownLatch与Thread.join() CyclicBarrier 实现分析 CountDownLatch和CyclicBa ...
随机推荐
- 牛客小白月赛12J(序列自动机)
题目链接:https://ac.nowcoder.com/acm/contest/392/J 题目大意:给一个字符串s,然后在给出n个其他的字符串,判断每个字符串是否为s的子序列. 例: 输入: no ...
- Python3 与 C# 面向对象之~异常相关
周末多码文,昨天晚上一篇,今天再来一篇: 在线编程:https://mybinder.org/v2/gh/lotapp/BaseCode/master 在线预览:http://github.les ...
- A1111. Online Map
Input our current position and a destination, an online map can recommend several paths. Now your jo ...
- tfs 2013 利用 web deploy 完成asp.net站点自动发布
课题起因: 目前我们团队使用visual studio 2013开发asp.net项目, 使用tfs2013 做源码管理, 每天早上手动发布项目文件包,复制到测试服务器的站点文件夹下覆盖老文件,用此方 ...
- px转换成bp单位的工具函数
import {Dimensions} from 'react-native' //当前屏幕的高度 const deviceH = Dimensions.get('window').height // ...
- Remote debugger is in a background tab which may cause apps to perform slowly. Fix this by foregrounding the tab (or opening it in a separate window).
先上代码: /** * Sample React Native App * https://github.com/facebook/react-native * * @format * @flow * ...
- Vue中data返回对象和返回值的区别
速记:粗浅的理解是,事件的结果是影响单个组件还是多个组件.因为大部分组件是要共享的,但他们的data是私有的,所以每个组件都要return一个新的data对象 返回对象的时候 <!DOCTYPE ...
- 跟我一起用node-express搭建一个小项目(mongodb)[二]
我的小项目主要是会用到MongoDB. 呵呵,我也是现学现卖. 都说小公司十八般武艺样样稀疏,没有办法啊! 兵来兵挡,将来将挡!自己是个兵呢?还是一个将呢! 没有公司培养,就自己培养自己呗.差的远一点 ...
- [LNOI2014]LCA(树链剖分+线段树)
题目链接:https://www.lydsy.com/JudgeOnline/problem.php?id=3626 题解:看到LCA,我们可以直接想到这题的正解不是LCA!(LCA只能得20分,还要 ...
- Oracle 常用的十大 DDL 对象
table:(表) 创建表 create table test3 (tid number,tname varchar2(),hiredate date default sysdate); create ...