需求
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";
}