In business scenario, InterruptException occurs multiple times, some before the business code is executed, and some after the business code. How to deal with InterruptException makes me confused.
1. preBusiness code semaphore.acquire()
try {
semaphore.acquire();
} catch (InterruptedException e) {
// do something
}
resObj = caller.stepTry();
semaphore.release();
postBusiness code
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 } }
There are also some doubts found in practice, and I am still thinking about how to draw conclusions. A thread can't be interrupted casually. Even if we set the interrupt state for the thread, it can still get the CPU time slice. Usually only threads blocked by the sleep() method can immediately receive an InterruptedException, so in the case of a sleep interrupt task, you can use try-catch to jump out of the task. In other cases, it is necessary to determine whether the task needs to be jumped out (Thread.interrupted() method) by judging the thread state.
In addition, the code modified by the synchronized method will not be interrupted immediately after receiving the interrupt signal. The synchronization code of the ReentrantLock lock control can be interrupted by InterruptException.