ExecutorService exec = Executors.newCachedThreadPool();
for(int i = 0; i < 10; i++)
{
exec.execute(new Entrance(i));//obviously Entrance is another class which implements Runnable
}
TimeUnit.SECONDS.sleep(3); // this sleep code is very elegant!
exec.shutdown();
if(!exec.awaitTermination(250, TimeUnit.MILLISECONDS))
{
print("Some tasks were not terminated");
}
Some points to explain:
1)ExecutorService.awaitTermination() waits for each task to complete, and if they all complete before the timeout value, it returns true, otherwise it returns false to indicate that not all tasks have completed.
本文介绍了如何利用Java中的ExecutorService来创建和管理线程池。通过newCachedThreadPool方法创建了一个可以缓存线程的线程池,并展示了如何提交任务到线程池中执行。此外,还讲解了如何优雅地关闭线程池并等待所有任务完成。
5782

被折叠的 条评论
为什么被折叠?



