简体   繁体   English

Android,Java:ExecutorService在关机后执行

[英]Android, Java: ExecutorService execute after shutdown

I have a ExecutorService : 我有一个ExecutorService

private final ExecutorService listenDataExecutorService = 
                              Executors.newSingleThreadExecutor();

In same case I need executor to stop doing his job. 在同样的情况下,我需要执行人员停止工作。 For this I call listenDataExecutorService.shutdown(); 为此,我调用listenDataExecutorService.shutdown();

Then after some time, I need this executor to do this job again. 然后过了一段时间,我需要这个执行者再次完成这项工作。 But when I call listenDataExecutorService.execute() exception is thrown. 但是当我调用listenDataExecutorService.execute()抛出异常。

How can I execute new task for executor after shutdown ? 如何在shutdown后执行执行程序的新任务?

Once an executor service has been shut down it can't be reactivated. 一旦执行程序服务关闭,它就无法重新激活。 Create a new executor service to restart execution: 创建新的执行程序服务以重新启动执行:

listenDataExecutorService = Executors.newSingleThreadExecutor();

(You'd have to drop the final modifier though.) (你必须删除final修饰符。)

Another option is to cancel all pending tasks instead, and then reschedule them when you want to resume execution. 另一种选择是取消所有挂起的任务,然后在您想要恢复执行时重新安排它们。

First you have to remove final access level modifier to re-create ExecutorService at latter stage. 首先,您必须删除final访问级别修饰符,以便在后期重新创建ExecutorService final modifier does not allow you to change the reference of ExecutorService later during re-initialization. final修饰符不允许您稍后在重新初始化期间更改ExecutorService的引用。

In same case I need executor to stop doing his job. 在同样的情况下,我需要执行人员停止工作。 For this I call listenDataExecutorService.shutdown(); 为此,我调用listenDataExecutorService.shutdown();

You have to call three methods in a right sequence to shutdown the ExecutorService : shutdown, awaitTermination, shutdownNow 您必须以正确的顺序调用三个方法来关闭ExecutorServiceshutdown, awaitTermination, shutdownNow

Have a look at below post: 看看下面的帖子:

How to properly shutdown java ExecutorService 如何正确关闭java ExecutorService

Then after some time, I need this executor to do this job again. 然后过了一段时间,我需要这个执行者再次完成这项工作。 But when I call listenDataExecutorService.execute() exception is thrown. 但是当我调用listenDataExecutorService.execute()抛出异常。

How can I execute new task for executor after shutdown ? 如何在关机后执行执行程序的新任务?

Before you call execute on that ExecutorService , that service should not be in shutdown state. 在对该ExecutorService调用execute之前,该服务不应处于shutdown状态。 Make sure that ExecutorService is in proper state to accept tasks => Your application code should properly handle " shutdown " and " re-creation " of ExecutorService . 确保ExecutorService处于正确状态以接受任务=>您的应用程序代码应正确处理ExecutorService关闭 ”和“ 重新创建 ”。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM