关键词:Java,线程,线程池,ExecutorService,ThreadPoolExecutor
目标:等待线程池里的子线程正常执行完毕。
方案:使用ThreadPoolExecutor
的getActiveCount
来判断是否还有活动线程,如果没有则认为子线程全部结束了。
ExecutorService executor = Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors() + 2);
if (!executor.isShutdown()) {
executor.execute(new XXXXXRunner(arg));
}
try {
ThreadPoolExecutor pool = (ThreadPoolExecutor) this.executor;
int activeThreadCnt = 0;
do {
this.executor.awaitTermination(1, TimeUnit.SECONDS);
activeThreadCnt = pool.getActiveCount();
} while (activeThreadCnt > 0);
} catch (InterruptedException e) {
e.printStackTrace();
}
文档信息
- 本文作者:zhupite
- 本文链接:https://zhupite.com/android/java-wait-all-thread-done.html
- 版权声明:自由转载-非商用-非衍生-保持署名(创意共享3.0许可证)