Future.get(timeout) 在给定超时后不会可靠地抛出 TimeoutException。这是正常行为还是我可以做些什么来使它更可靠?这个测试在我的机器上失败了。但是,如果我睡 3000 而不是 2000,它就会过去。
public class FutureTimeoutTest {
@Test
public void test() throws
ExecutionException,
InterruptedException {
ExecutorService exec = Executors.newSingleThreadExecutor();
final Callable call = new Callable() {
@Override
public Object call() throws Exception {
try {
Thread.sleep(2000);
} catch (InterruptedException ex) {
ex.printStackTrace();
}
return 0;
}
};
final Future future = exec.submit(call);
try {
future.get(1000, TimeUnit.MILLISECONDS);
fail("expected TimeoutException");
} catch (TimeoutException ignore) {
}
}
}