項目中遇到線程池異步處理Callable請求,阻塞接收future.get()結果時,對線程中斷狀態位state的處理問題。
try {
Future<Object> future = executor.submit(callcable);
future.get();
} catch (InterruptedException e) {
Thread.interrupted(); // 重置當前線程的中斷位state為false,便於該線程以后被其他任務正常調用
}
對項目中的這種處理感到疑惑,翻了下源碼中具體的實現細節,發現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異常處理亦是如此。