如何在一定次数的启动之后或特定值返回时停止 ScheduledExecutorService?

huangapple 未分类评论59阅读模式
英文:

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

  1. 一旦您将任务提交给ScheduledExecutorService,如果任务完成其工作,那么任务/线程将由JVM自动停止。

  2. 如果任务花费太长时间来响应,或者您希望在执行过程中停止它,您可以使用future.cancel(true)来中断任务/线程。

  3. 最后,您应该通过调用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块中执行相同操作。
英文:
  1. Once you submit task to ScheduledExecutorService, if task complete it's jobs then the task/thread automatically stop by the
    JVM.
  2. If task takes to long to respond or you want stop in middle of execution, you can interrupt task/thread using
    future.cancel(true).
  3. 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&lt;String&gt; task = () -&gt; {
        return &quot;task1 completed&quot;;
    };
    String taskResponse = null;
    Future&lt;String&gt; 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.

huangapple
  • 本文由 发表于 2020年7月28日 20:54:39
  • 转载请务必保留本文链接:https://java.coder-hub.com/63134628.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定