如何阻止下一个线程在ScheduledThreadPoolExecutor中运行

时间:2016-05-19 08:57:57

标签: java multithreading executorservice threadpoolexecutor executor

我有一个ScheduledThreadPoolExecutor,它有一个线程并且每30秒运行一次。

现在,如果当前正在执行的线程抛出一些异常,那么我需要确保下一个线程不运行并且ScheduledThreadPoolExecutor已关闭。

我如何实现这一目标?

2 个答案:

答案 0 :(得分:1)

作为一种简洁的方法,您只需使用静态访问类来设置/检查执行可用性。

import java.util.concurrent.atomic.AtomicBoolean;

class ThreadManager
{
    private static AtomicBoolean shouldStop = new AtomicBoolean(false);

    public static void setExceptionThrown(boolean val)
    {
        shouldStop.set(val);
    }

    public boolean shouldExecuteTask()
    {
        return !shouldStop.get();
    }
}

一个自定义的可运行实现,允许您检查执行任务的可能性

abstract class ModdedRunnable implements Runnable
{
    @Override
    public void run()
    {
        if(ThreadManager.shouldExecuteTask())
        {
            try
            {
                runImpl();
            }
            catch(Exception t)
            {
                ThreadManager.setExceptionThrown(true);
            }
        }
    }

    public abstract void runImpl() throws Exception;
}

答案 1 :(得分:1)

ExecutorService

中捕获异常调用shutdown / shutdownNow API

<强> shutdown()方法

启动有序关闭,其中先前提交的任务已执行,但不会接受任何新任务。如果已经关闭,调用没有其他影响。 此方法不会等待先前提交的任务完成执行。 使用awaitTermination执行此操作

<强>执行shutdownNow()

尝试停止所有正在执行的任务,停止等待任务的处理,并返回等待执行的任务列表。 此方法不等待主动执行任务终止。 使用awaitTermination执行此操作

除了尽力尝试停止处理主动执行任务之外,没有任何保证。例如,典型的实现将通过Thread.interrupt()取消,因此任何无法响应中断的任务都可能永远不会终止。

有关工作代码的详细信息,请参阅这些帖子。

How to forcefully shutdown java ExecutorService

相关问题