我使用ScheduledExecutorService在固定的1 min时间间隔内运行线程。
ScheduledExecutorService的一个实例运行一个线程,另一个实例运行另一个线程。
示例:
ses1.scheduleAtFixRate(..) // for thread 1
ses2.scheduleAtFixRate(..) // for thread 2我遇到了一些异常,由此停止了进一步的执行。我想捕捉我的应用程序系统关闭的异常。
应该使用监视期货和处理异常的第三个线程来处理异常,还是有其他更好的方法?会影响其他线程吗。
任何和所有的帮助都是感激的!
发布于 2019-08-03 07:27:12
我遇到了一些异常,由此停止了进一步的执行。
根据规范,这是ScheduledExecutorService.scheduleAtFixRate()的预期行为:
如果任务的任何执行遇到异常,则随后的执行将被抑制。
关于你的需要:
我想捕捉我的应用程序系统关闭的异常。 我应该使用第三个线程来监控期货和处理异常,还是有其他更好的方法来处理异常?
使用ScheduledFuture.get()处理未来的返回似乎是正确的。根据ScheduledFuture.scheduleAtFixedRate()规范:
否则,任务将仅通过取消或终止执行器来终止。
所以你甚至不需要创造一个新的计划未来。
只需运行两个并行任务(也可以使用ExecutorService或两个线程),这些任务等待每个Future的get()并在任务中抛出异常时停止应用程序:
Future<?> futureA = ses1.scheduleAtFixRate(..) // for thread 1
Future<?> futureB = ses2.scheduleAtFixRate(..) // for thread 2
submitAndStopTheApplicationIfFail(futureA);
submitAndStopTheApplicationIfFail(futureB);
public void submitAndStopTheApplicationIfFail(Future<?> future){
executor.submit(() -> {
try {
future.get();
} catch (InterruptedException e) {
// stop the application
} catch (ExecutionException e) {
// stop the application
}
});
}https://stackoverflow.com/questions/57336040
复制相似问题