Java ScheduledExecutorService 启动停止几次
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4205327/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
ScheduledExecutorService start stop several times
提问by walters
I am using ScheduledExecutorService, and after I call it's shutdownmethod, I can't schedule a Runnable on it. Calling scheduleAtFixedRate(runnable, INITIAL_DELAY,
INTERVAL, TimeUnit.SECONDS)
after shutdown()
throws java.util.concurrent.RejectedExecutionException. Is there another way to run a new task after shutdown()
is called on ScheduledExecutorService?
我正在使用ScheduledExecutorService,在我调用它的关闭方法之后,我无法在它上面安排一个 Runnable 。scheduleAtFixedRate(runnable, INITIAL_DELAY,
INTERVAL, TimeUnit.SECONDS)
在shutdown()
抛出 java.util.concurrent.RejectedExecutionException之后调用。shutdown()
在ScheduledExecutorService上调用之后是否有另一种方法来运行新任务?
采纳答案by Alex Objelean
You can reuse the scheduler, but you shouldn't shutdown it. Rather, cancel the running thread which you can get when invoking scheduleAtFixedRate method. Ex:
您可以重用调度程序,但不应关闭它。相反,取消调用 scheduleAtFixedRate 方法时可以获得的正在运行的线程。前任:
//get reference to the future
Future<?> future = service.scheduleAtFixedRate(runnable, INITIAL_DELAY, INTERVAL, TimeUnit.SECONDS)
//cancel instead of shutdown
future.cancel(true);
//schedule again (reuse)
future = service.scheduleAtFixedRate(runnable, INITIAL_DELAY, INTERVAL, TimeUnit.SECONDS)
//shutdown when you don't need to reuse the service anymore
service.shutdown()
回答by Peter Knego
The javadocs of shutdown()
say:
的 javadocsshutdown()
说:
Initiates an orderly shutdown in which previously submitted tasks are executed,
but no new tasks will be accepted.
So, you cannot call shutdow()
and then schedule new tasks.
因此,您无法调用shutdow()
然后安排新任务。
回答by Kent Murra
You can't make your executor accept new tasks after shutting it down. The more relevant question is why you need to shut it down in the first place? The executors you create should be re-used across the lifetime of your application or sub-system.
你不能让你的执行器在关闭后接受新任务。更相关的问题是为什么首先需要关闭它?您创建的执行程序应该在您的应用程序或子系统的整个生命周期内重复使用。