java – 一旦我认为它完成,如何在ScheduledThreadPoolExecutor中停止任务

前端之家收集整理的这篇文章主要介绍了java – 一旦我认为它完成,如何在ScheduledThreadPoolExecutor中停止任务前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我有一个ScheduledThreadPoolExecutor,我计划任务以固定的速率运行.我希望任务以指定的延迟运行,最多为10次,直到“成功”为止.之后,我不想让任务重试.所以基本上我需要停止运行计划的任务,当我想要停止它,但不关闭ScheduledThreadPoolExecutor.任何想法我该怎么做?

这里有一些伪代码

public class ScheduledThreadPoolExecutorTest
{
  public static ScheduledThreadPoolExecutor executor = new ScheduledThreadPoolExecutor(15);  // no multiple instances,just one to serve all requests

  class MyTask implements Runnable
  {
    private int MAX_ATTEMPTS = 10;
    public void run()
    {
      if(++attempt <= MAX_ATTEMPTS)
      {
        doX();
        if(doXSucceeded)
        {
          //stop retrying the task anymore
        }
      }
      else
      { 
        //couldn't succeed in MAX attempts,don't bother retrying anymore!
      }
    }
  }

  public void main(String[] args)
  {
    executor.scheduleAtFixedRate(new ScheduledThreadPoolExecutorTest().new MyTask(),5,TimeUnit.SECONDS);
  }
}

解决方法

运行此测试,打印1 2 3 4 5并停止
public class ScheduledThreadPoolExecutorTest {
    static ScheduledThreadPoolExecutor executor = new ScheduledThreadPoolExecutor(15); // no
    static ScheduledFuture<?> t;

    static class MyTask implements Runnable {
        private int attempt = 1;

        public void run() {
            System.out.print(attempt + " ");
            if (++attempt > 5) {
                t.cancel(false);
            }
        }
    }

    public static void main(String[] args) {
        t = executor.scheduleAtFixedRate(new MyTask(),1,TimeUnit.SECONDS);
    }
}
原文链接:https://www.f2er.com/java/124852.html

猜你在找的Java相关文章