我想在ExecutorService中停止所有任务。
现在我试试:
mExecutor.shutdownNow();
// Prepare Scroller data
mExecutor.execute(new Scroller(destination, speed));
但我抓住了异常
F/RH2.C.AndroidRuntime(20514): java.util.concurrent.RejectedExecutionException: Task ### rejected from java.util.concurrent.ThreadPoolExecutor@425a3ab0[Terminated, pool size = 0, active threads = 0, queued tasks = 0, completed tasks = 0]
F/RH2.C.AndroidRuntime(20514): at java.util.concurrent.ThreadPoolExecutor$AbortPolicy.rejectedExecution(ThreadPoolExecutor.java:1979)
F/RH2.C.AndroidRuntime(20514): at java.util.concurrent.ThreadPoolExecutor.reject(ThreadPoolExecutor.java:786)
F/RH2.C.AndroidRuntime(20514): at java.util.concurrent.ThreadPoolExecutor.execute(ThreadPoolExecutor.java:1307)
F/RH2.C.AndroidRuntime(20514): at java.util.concurrent.Executors$DelegatedExecutorService.execute(Executors.java:552)
我如何解决这个问题?
P.S。我的多线程知识是如此之低,所以如果你解释我为什么会有这个例外,我会很高兴。感谢。
答案 0 :(得分:1)
mExecutor.shutdownNow();
// Prepare Scroller data
mExecutor = Executors.newCachedThreadPool();//or other pool which u need
mExecutor.execute(new Scroller(destination, speed));
By this way u can go.
答案 1 :(得分:0)
在Executor上调用shutdownNow()
方法后。
您无法向其提交任何新的Runnable / Thread实例。如果你试图这样做,它会给你这个例外。
答案 2 :(得分:0)
当您在执行程序已经关闭时尝试提交作业/任务时,会获得RejectedExecutionException。 要解决此问题,您必须确保Executor已启动并运行。 在提交作业之前,检查执行程序正在运行。
mExecutor.shutdownNow();
// Prepare Scroller data
if(mExecutor == null || mExecutor.isShutdown()) {
//whatever your executor type is, create new instance is its shutdown already
mExecutor = Executors.newSingleThreadScheduledExecutor();
}
mExecutor.execute(new Scroller(destination, speed));
有关详细信息,请查看此链接,其中包含一些示例代码: http://handling-thread.blogspot.co.uk/2012/05/pause-and-resume-thread.html