简体   繁体   English

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

[英]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?或者也许有更合适的工具?

  1. Once you submit task to ScheduledExecutorService, if task complete it's jobs then the task/thread automatically stop by the JVM.将任务提交给 ScheduledExecutorService 后,如果任务完成它的作业,则任务/线程会在 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).如果任务需要很长时间才能响应或者你想在执行过程中停止,你可以使用 future.cancel(true) 中断任务/线程。
  3. At the end you should shutdown ScheduledExecutorService by calling shutdown method on it.最后,您应该通过调用 shutdown 方法来关闭 ScheduledExecutorService。

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM