【问题标题】:Interrupt and restart tasks when using ScheduledThreadPoolExecutor使用 ScheduledThreadPoolExecutor 时中断和重启任务
【发布时间】:2013-02-28 19:55:24
【问题描述】:

我在理解 ScheduledThreadPoolExecutor 的工作原理时遇到了一点问题(我使用的是 SCA,所以不要理会代码中的注释)。这是我的调度程序类代码的一部分:

@AllowsPassByReference
public ScheduledFuture<?> schedule(Task task)
{
    future=scheduler.scheduleAtFixedRate(task.getRunnableContent(), task.getDelay(), task.getPeriod(), TimeUnit.MILLISECONDS);
    return future;
}

@AllowsPassByReference
public void deschedule(Task task)
{
    scheduler.remove(task.getRunnableContent());
}

这是我的任务类代码的一部分:

public void scheduleTask()
{
    if(!running)
    {
        future=scheduler.schedule(this);
        running=true;
    }
}

public void descheduleTask()
{
    if(running)
    {
        future.cancel(mayInterruptIfRunning);
        scheduler.deschedule(this);
        running=false;
    }
}

现在最重要的是!我到处看到人们在 ScheduledFutures 上使用取消,然后在调度程序上使用关闭方法,但我不想停止调度程序。让我稍微解释一下:在这个应用程序中,周期性任务必须在任何时候单独调度、停止和重新调度,所以我需要一种方法来在单个任务开始运行时中断它,而无需关闭整个调度程序服务。我希望你能理解我在做什么,有什么建议吗?谢谢:)

【问题讨论】:

    标签: java scheduled-tasks scheduler interrupt futuretask


    【解决方案1】:

    当我们取消一个周期性任务时,这个任务后续的调度会被取消,但是调度器本身会运行,可以用来调度另一个任务。

    如果我们在任务运行时调用 Future.cancel 那么

    a) Future.cancel(false) 不会影响正在运行的任务

    b) Future.cancel(true) 会在任务的线程上调用 Threed.interrupt,但是正在运行的任务是否会停止取决于任务的实现。例如,任务可能会捕获 InterruptedException(如果有)并继续工作。

    【讨论】:

    • 感谢您的回答,至少现在我知道我遇到的问题一定与 SCA 如何管理我的课程有关
    猜你喜欢
    • 2013-10-09
    • 1970-01-01
    • 1970-01-01
    • 2011-05-29
    • 2013-05-20
    • 1970-01-01
    • 2013-01-29
    • 2020-01-12
    • 1970-01-01
    相关资源
    最近更新 更多