如何在Android应用程序中使用ExecutorService shutdown

时间:2015-12-10 20:36:05

标签: java android multithreading executorservice

我正在编写一个带有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类旨在在整个应用程序中用于运行任务/ Runnables,而doSomething()函数用于在单个线程中排队并运行所有Runnables。

但有一点我无法弄清楚何时调用ExecutorService。 shutdown()方法。如果我这样称呼它:

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

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

有人可以向我展示一些关于何时/如何在Android应用程序中调用ExecutorService.shutdown()的提示?感谢

2 个答案:

答案 0 :(得分:0)

每次执行某项任务时都没有充分的理由来调用shutdown。您可能希望在关闭/完成应用程序的某些部分时调用shutdown。 IE浏览器。当Service停止时 - 如果它使用了执行程序 - 那么我认为你应该关闭它们 - 但实际上重点是允许所有任务在服务退出逻辑执行一些完成代码之前完成。即。使用:

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

作为一个例子,这样的服务可以用来下载一些文件,用户就是。想暂停下载 - 即。通过打开相机应用程序(可能会停止您的应用程序/服务来回收其资源/内存)。

答案 1 :(得分:0)

在 Android 应用程序中,除非有空闲线程,否则无需关闭单例 ExecutorService。根据 Android docs

<块引用>

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

因此,如果您使用 Executors.newCachedThreadPool() 或创建一个 corePoolSize 为 0 的 ThreadPoolExecutor,它将在应用程序进程终止时自动关闭。