小编刘海翔*_*刘海翔的帖子

处理 InterruptedException 的最佳实践

在业务场景中,InterruptException 会发生多次,有的在业务代码执行之前,有的在业务代码执行之后。如何处理 InterruptException 让我很困惑。

     1.业务前代码 semaphore.acquire()

        try {
            semaphore.acquire();
        } catch (InterruptedException e) {
           // do something
        }
        resObj = caller.stepTry();
        semaphore.release();
Run Code Online (Sandbox Code Playgroud)
  1. 邮政编码 latch.await()service.take().get()

    CompletionService<CallableResultBO> service = new ExecutorCompletionService<>(executor);
    CountDownLatch latch = new CountDownLatch(size);
    
    for (R callable : listCall){
        callable.setCountParam(JdkThreadCountBO.buildByLatch(latch));
        service.submit(callable);
    }
    
    try {
        latch.await();
    } catch (InterruptedException e) {
        // do something
    }
    
    CallableResultBO[] resArr = new CallableResultBO[size];
    for ( int i = 0; i < size; i++ …
    Run Code Online (Sandbox Code Playgroud)

java concurrency exception

5
推荐指数
2
解决办法
4154
查看次数

标签 统计

concurrency ×1

exception ×1

java ×1