英文:
How to stop ScheduledExecutorService after a certain number of starts or when a certain value returns?
问题
我使用 ScheduledExecutorService
来以固定速率执行2个任务 scheduleAtFixedRate
。这两个任务都会返回一个值。如何在一定次数的启动后或某个特定值返回时停止任务的执行?或者也许有更适合的工具可以实现这一点?
英文:
I use a ScheduledExecutorService
to execute 2 tasks at a fixed rate scheduleAtFixedRate
. Both of these tasks return a value. How to stop execution of a task after a certain number of starts or when a certain value returns? Or maybe there are more suitable tools for this?
答案1
得分: 0
-
一旦您将任务提交给ScheduledExecutorService,如果任务完成其工作,那么任务/线程将由JVM自动停止。
-
如果任务花费太长时间来响应,或者您希望在执行过程中停止它,您可以使用future.cancel(true)来中断任务/线程。
-
最后,您应该通过调用shutdown方法来关闭ScheduledExecutorService。
希望下面的代码对您有帮助:
ScheduledExecutorService service = Executors.newScheduledThreadPool(2); // 池大小
Callable<String> task = () -> {
return "task1 completed";
};
String taskResponse = null;
Future<String> future = service.submit(task);
// 应用程序线程等待任务完成。
while (!future.isDone()) {
// 等待特定时间,或者您可以中断线程/任务,如下所示
// future.cancel(true),它将中断任务/线程。
}
if (future.isDone()) {
taskResponse = future.get();
}
// 在最后调用Executor服务关闭
service.shutdown(); // 您也可以在finally块中执行相同操作。
英文:
- Once you submit task to ScheduledExecutorService, if task complete it's jobs then the task/thread automatically stop by the
JVM. - If task takes to long to respond or you want stop in middle of execution, you can interrupt task/thread using
future.cancel(true). - At the end you should shutdown ScheduledExecutorService by calling shutdown method on it.
Hope below code help you,
ScheduledExecutorService service = Executors.newScheduledThreadPool(2);//pool size
Callable<String> task = () -> {
return "task1 completed";
};
String taskResponse = null;
Future<String> future = service.submit(task);
// Application thread wait for task to complete.
while (!future.isDone()){
// wait specific time or you can interrupt thread/task as below
//future.cancel(true), it will interrupt task/thread.
}
if(future.isDone()){
taskResponse = future.get();
}
// at end call Executor service shutdown
service.shutdown();// you can do the same at finally block also.
专注分享java语言的经验与见解,让所有开发者获益!
评论