在 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();
}
}
}