<分区>
在业务场景中,InterruptException多次出现,有的出现在业务代码执行之前,有的出现在业务代码之后。如何处理 InterruptException 让我很困惑。
1. preBusiness code semaphore.acquire()
try {
semaphore.acquire();
} catch (InterruptedException e) {
// do something
}
resObj = caller.stepTry();
semaphore.release();
postBusiness代码
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++ ){ try { resArr[i] = service.take().get(); } catch (InterruptedException e) { // do something } catch (ExecutionException e) { // do something } }
实践中也发现了一些疑点,目前还在思考如何下结论。 一个线程不能随便中断。即使我们为线程设置了中断状态,它仍然可以获得CPU时间片。通常只有被sleep()方法阻塞的线程才能立即收到InterruptedException,所以在 sleep 中断任务的情况下,可以使用try-catch跳出任务。其他情况需要通过判断线程状态来判断任务是否需要跳出(Thread.interrupted()方法)。
另外,synchronized方法修改的代码在收到中断信号后不会立即中断。 ReentrantLock锁控件的同步代码可以被InterruptException中断。