我有以下两个类
public class TimeoutHandler
{
private int timeoutMsec = 10000;
private ScheduledExecutorService scheduler;
private ScheduledFuture<String> future;
public TimeoutHandler()
{
}
public TimeoutHandler(int msec)
{
timeoutMsec = msec;
}
public void startTimeoutHandler() throws TimeoutException
{
scheduler = Executors.newScheduledThreadPool(1);
future = scheduler.schedule(new TimeoutCallable(), timeoutMsec, TimeUnit.MILLISECONDS);
}
}
和
public class TimeoutCallable implements Callable<String>
{
@Override
public String call() throws TimeoutException
{
throw new TimeoutException();
}
}
现在我使用方法TimeoutHandler
启动startTimeoutHandler()
,它应该安排将来的线程从timeoutMsec
开始。问题是,永远不会调用TimeoutCallable
,并且永远不会启动throw new TimeoutException();
。有什么建议吗?
答案 0 :(得分:0)
我们需要调用future.get()
来检索结果,如果以ExectuorException
的形式提供,此函数将抛出异常:可以在异常上调用getCause()
来检索原因。如下所示:
try {
future.get();
} catch (InterruptedException ex) {
Logger.getLogger(CallableTest.class.getName()).log(Level.SEVERE, null, ex);
} catch (ExecutionException ex) {
System.out.println(ex.getCause());
//Logger.getLogger(CallableTest.class.getName()).log(Level.SEVERE, null, ex);
}
<强>输出:强>
java.util.concurrent.TimeoutException