How to stop next thread from running in a ScheduledThreadPoolExecutor

家住魔仙堡 提交于 2019-12-18 09:41:00

问题


I have a ScheduledThreadPoolExecutor which has one thread and runs for every 30 seconds.

Now, if the current executing thread throws some exception, then I need to make sure that the next thread do not run and the the ScheduledThreadPoolExecutor is down.

How do I achieve this?


回答1:


As a clean way, you can simply use a static accessed class to set/check the execution availability.

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

And a custom runnable implementation that allows you to check for the possibility to execute the task

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



回答2:


Catch the exception call shutdown/shutdownNow API in ExecutorService

shutdown()

Initiates an orderly shutdown in which previously submitted tasks are executed, but no new tasks will be accepted. Invocation has no additional effect if already shut down. This method does not wait for previously submitted tasks to complete execution. Use awaitTermination to do that.

shutdownNow()

Attempts to stop all actively executing tasks, halts the processing of waiting tasks, and returns a list of the tasks that were awaiting execution. This method does not wait for actively executing tasks to terminate. Use awaitTermination to do that.

There are no guarantees beyond best-effort attempts to stop processing actively executing tasks. For example, typical implementations will cancel via Thread.interrupt(), so any task that fails to respond to interrupts may never terminate.

Refer to these post for more details with working code.

How to forcefully shutdown java ExecutorService



来源:https://stackoverflow.com/questions/37318461/how-to-stop-next-thread-from-running-in-a-scheduledthreadpoolexecutor

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!