static ExecutorService executorService = Executors.newCachedThreadPool();
/**
* get 出現TimeoutException,並不會中斷或者取消運算線程
* @throws InterruptedException
*/
@Test
void testGetTimeoutException() throws InterruptedException {
final Future<Long> future = executorService.submit(() -> {
delay(3000);
System.out.println("delay 3000");
return 888L;
});
try {
final long value = future.get(1, TimeUnit.SECONDS);
System.out.println("value = " + value);
Assertions.fail();
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
} catch (TimeoutException e) {
// get timeout
System.out.println("get timeout");
}
executorService.shutdown();
executorService.awaitTermination(100, TimeUnit.SECONDS);
System.out.println("wait shutdown");
}
// 輸出
get timeout
delay 5000
wait shutdown