[英]How to stop ScheduledExecutorService after a certain number of starts or when a certain value returns?
I use a ScheduledExecutorService
to execute 2 tasks at a fixed rate scheduleAtFixedRate
.我使用
ScheduledExecutorService
以固定速率scheduleAtFixedRate
执行 2 个任务。 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?
或者也许有更合适的工具?
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.
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.