【问题标题】:How to stop next thread from running in a ScheduledThreadPoolExecutor如何停止下一个线程在 ScheduledThreadPoolExecutor 中运行
【发布时间】:2016-09-16 01:15:59
【问题描述】:

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

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

我如何做到这一点?

【问题讨论】:

  • 嗯...只需捕获异常并从捕获块中关闭执行程序。

标签: java multithreading executorservice threadpoolexecutor executor


【解决方案1】:

ExecutorService中捕获异常调用shutdown/shutdownNow API

关机()

启动有序关闭,其中执行先前提交的任务,但不会接受新任务。如果已经关闭,调用没有额外的效果。 此方法不等待先前提交的任务完成执行。 使用 awaitTermination 来做到这一点

shutdownNow()

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

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

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

How to forcefully shutdown java ExecutorService

【讨论】:

    【解决方案2】:

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

    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;
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-01-12
      • 2020-05-05
      • 2012-05-19
      • 2014-04-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多