如何在我认为完成后停止 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(), 0, 5, TimeUnit.SECONDS);
  }
}

答案 1

运行此测试,它打印并停止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(), 0, 1, TimeUnit.SECONDS);
    }
}

答案 2

在线程外部很好地取消:

public class ScheduleTest {

    @Test
    public void testCancel() throws Exception {
        final ScheduledThreadPoolExecutor EXECUTOR = (ScheduledThreadPoolExecutor) Executors.newScheduledThreadPool(2);
        ScheduledFuture f1 = EXECUTOR.scheduleAtFixedRate(new Runnable() {
            @Override
            public void run() {
                System.out.println("Im alive 1");
            }
        }, 0, 1, TimeUnit.SECONDS);
        ScheduledFuture f2 = EXECUTOR.scheduleAtFixedRate(new Runnable() {
            @Override
            public void run() {
                System.out.println("Im alive 2");
            }
        }, 0, 2, TimeUnit.SECONDS);

        Thread.sleep(10000);
        f1.cancel(true);
        System.out.println("f1 cancel");
        Thread.sleep(10000);
        f2.cancel(false);
        System.out.println("f2 cancel");
        Thread.sleep(10000);
    }
}

有时线程无法取消,这通常通过以下方式解决volatile boolean isCancelled;


推荐