这是我的主要方法:
public static void main(String... args) throws ClassNotFoundException {
String[] classAndMethod = args[0].split("#");
if (helpCmd(args)) {
printHelpForTest(classAndMethod[1]);
System.exit(0);
}
Result result = runTest(classAndMethod);
exitIfTimeOutExceptionThrown(result);
System.exit(result.wasSuccessful() ? 0 : 1);
}
private static void exitIfTimeOutExceptionThrown(Result result) {
boolean isTimeOut = Iterables.filter(result.getFailures(), CodeBlockTimeOutException.class).iterator().hasNext();
if (isTimeOut)
{
System.exit(2);
}
}
运行此junit测试的:
@Test
public void sendSearchRequest() throws Exception {
...
setTimeOut();
...
}
private void setTimeOut() {
if (criticalBlockTimeOut != null) {
TimerTask timerTask = new TimerTask() {
@Override
public void run() {
throw new CodeBlockTimeOutException();
//thread.interrupt();
}
};
new Timer().schedule(timerTask, Long.parseLong(criticalBlockTimeOut));
}
}
为什么我看到我的代码抛出了CodeBlockTimeOutException
,但它主要永远不会退出代码2?
我怎么能把它扔到主线程中?
答案 0 :(得分:6)
计时器事件发生在另一个线程中。主线程退出没有错误。从另一个记录错误。如果出现异常,您应该从预定作业中设置一些易失性标志。等待作业在主线程中完成,然后检查此标志。
在这里查看:Waiting for a Timer to finish in Java或Java: Wait for TimerTask to complete before continuing execution