【发布时间】:2013-05-21 08:01:49
【问题描述】:
在 IntentService 中,我使用 ThreadPoolExecutor poolSize 8 和 maxPoolSize 10。无论何时启动 Service,都会影响 UI。在 runTask() 方法中,我将任务添加到线程池。
private ThreadPoolExecutor threadPool = null;
private final LinkedBlockingQueue<Runnable> threadsQueue =
new LinkedBlockingQueue<Runnable>();
private Collection<Future<?>> futures = new LinkedList<Future<?>>();
public MyService(String name) {
super(name);
threadPool = new ThreadPoolExecutor(poolSize, maxPoolSize, keepAliveTime,
TimeUnit.SECONDS, threadsQueue);
}
public void runTask(Runnable task) {
futures.add(threadPool.submit(task));
}
/**
* When ever we call this method it will hold the main thread untill the tasks
* in thread pool are completed.
*/
public void waitForThreadPool() {
for (Future<?> future : futures) {
try {
future.get();
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
}
【问题讨论】:
-
"在 IntentService 中,我使用 ThreadPoolExecutor poolSize 8 和 maxPoolSize 10。" ——这是一个可怕的想法。永远不要在
IntentService中做超出onHandleIntent()的事情,例如设置自己的线程池。如果您想在Service中拥有一个线程池,请使用常规的Service。除此之外,StackOverflow 是用于编程问题的,你还没有问过问题。 -
@CommonsWare 我想,它挂了,正如标题所暗示的那样
-
我也遇到了同样的问题,但得到了很好的解决方案,请按照我的回答stackoverflow.com/a/44432310/4997704
标签: android performance intentservice threadpoolexecutor