项目中遇到线程池异步处理Callable请求,阻塞接收future.get()结果时,对线程中断状态位state的处理问题。try {
Future future = executor.submit(callcable);
future.get();
} catch (InterruptedException e) {
Thread.interrupted(); // 重置当前线程的中断位state为true,便于该线程以后被其他任务正常调用
}
对项目中的这种处理感到疑惑,翻了下源码中具体的实现细节,发现Future的实现类FutureTask的get()方法如下:
public V get() throws InterruptedException, ExecutionException { int s = state; if (s <= COMPLETING) s = awaitDone(false, 0L); // throws InterruptedException
return report(s); // throws ExecutionException
}其中InterruptedException是awaitDone(false, 0L)方法抛出的:
if (Thread.interrupted()) { removeWaiter(q); throw new InterruptedException();}可以看出awaitDone(boolean timed, long nanos)方法中已经重置了状态位state,所以正常项目中捕获InterruptedException异常后,不需要再重新重置当前线程的状态位state。不过为了安全保险起见,Thread.interrupted()重置一下会更加便于项目中的理解;同时Process的实现类ProcessImpl的waitFor()抛出的InterruptedException异常处理亦是如此。
来源:https://www.cnblogs.com/septemberFrost/p/12015029.html