当前位置: 首页 > 知识库问答 >
问题:

如何在Android应用程序中使用ExecutorService关闭

端木皓君
2023-03-14

我正在编写一个带有ExecutorService的单例类的SDK。它看起来像这样:

public class MySingleton {
    private static MySingleton mInstance;
    private ExecutorService mExecutorService;

    private MySingleton() {
        mExecutorService = Executors.newSingleThreadExecutor();
    }

    // ...

    public void doSomething(Runnable runnable) {
        mExecutorService.execute(runnable);
    }
}

此SDK类用于在整个应用程序中运行任务/可运行程序,doSomething()函数用于在单个线程中排队并运行所有可运行程序。

但有一件事我搞不清楚,那就是什么时候给ExecutorService打电话。shutdown()方法。如果我这样称呼它:

public void doSomething(Runnable runnable) {
    if (mExecutorService.isTerminated()) {
        mExecutorService = Executors.newSingleThreadExecutor();
    }
    mExecutorService.execute(runnable);
    mExecutorService.shutdown();
}

它会破坏使用一个Thread的目的,因为如果在第二次调用doThings()时旧的Runnable仍在运行,可能会有两个不同的Thread同时运行。当然,我可以有一个手动关闭ExecutorService的函数,但要求SDK的用户显式调用关闭函数似乎不合适。

有人能告诉我一些何时/如何调用ExecutorService的提示吗。Android应用程序中的shutdown()?谢谢

共有2个答案

岳嘉悦
2023-03-14

在Android应用程序中,无需关闭singleton ExecutorService,除非它有任何空闲线程。根据Android文档:

程序中不再引用且没有剩余线程的池将自动关闭。如果要确保即使用户忘记调用shutdown(),也会回收未引用的池,则必须通过设置适当的保持活动时间、使用零核心线程的下限和/或设置allowCoreThreadTimeOut(布尔值),安排未使用的线程最终死亡。

因此,如果使用执行器。newCachedThreadPool()或创建corePoolSize为0的ThreadPoolExecutor,当应用程序进程死亡时,它将自动关闭。

缪风史
2023-03-14

没有充分的理由在每次执行某个任务时调用shutdown。您可能希望在关闭/完成应用程序的某些部分时调用shutdown。也就是说,当服务被停止时,如果它使用了执行器,那么我想你应该关闭它们,但实际上,关键是让所有任务在服务退出逻辑执行一些完成代码之前完成。即通过使用:

  executors.shutdown();
  if (!executors.awaitTermination(5, TimeUnit.SECONDS)) {
    executors.shutdownNow();
  }

例如,此类服务可用于下载某些文件,用户将即。想要暂停下载-即。通过打开相机应用程序(这可能会停止您的应用程序/服务以回收其资源/内存)。

 类似资料: