一个关于CountDownLatch的并发需求

发布时间 2023-06-09 03:19:25作者: 帅气的涛啊

需求

A,B,C可并发运行,全部成功才算成功,一个失败全员回滚。

思考

使用CountDownLatch,可以保证三个线程结束后,才进行提交成功状态。但是怎么才能判断某个任务失败了呢?

  1. 捕获子线程异常?
  2. 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";
    }