一个关于CountDownLatch的并发需求
需求
A,B,C可并发运行,全部成功才算成功,一个失败全员回滚。
思考
使用CountDownLatch,可以保证三个线程结束后,才进行提交成功状态。但是怎么才能判断某个任务失败了呢?
- 捕获子线程异常?
- await(long timeout, TimeUnit unit)?
陷入了沉思
加一个原子变量判断子线程异常的次数不就OK嘛(分布式用分布式锁,单机用原子类)
@GetMapping("/{id}")
String test(@PathVariable("id") String id) {
ThreadPoolExecutor threadPoolExecutor = ExecutorFactory.newCustomerThreadExecutor(3, 3, 1000, new NameThreadFactory("画像表"));
// 失败线程数
LongAdder failThreadNum = new LongAdder();
int threadSize = 2;
CountDownLatch cdl = new CountDownLatch(threadSize);
Thread t1 = new Thread(() -> {
try {
System.out.println(Thread.currentThread().getName());
if (Objects.equals(id, "1")) {
throw new RuntimeException();
}
} catch (Exception e) {
failThreadNum.increment();
} finally {
cdl.countDown();
}
});
Thread t2 = new Thread(() -> {
try {
System.out.println(Thread.currentThread().getName());
} catch (Exception e) {
failThreadNum.increment();
} finally {
cdl.countDown();
}
});
threadPoolExecutor.submit(t1);
threadPoolExecutor.submit(t2);
try {
cdl.await();
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
if (failThreadNum.intValue() != 0) {
System.out.println("回滚");
} else {
System.out.println("Main over");
}
threadPoolExecutor.shutdown();
return "success";
}
本文来自博客园,作者:帅气的涛啊,转载请注明原文链接:https://www.cnblogs.com/handsometaoa/p/17468104.html
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 分享4款.NET开源、免费、实用的商城系统
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 记一次.NET内存居高不下排查解决与启示
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了