Java中如何使用ExecutorService等待所有线程完成呢?
下文笔者讲述ExecutorService等待所有线程完成的方法分享,如下所示
在使用Executor时 我们可以使用shutdown()或shutdownNow()方法将其关闭 但是这种方式,不会等到所有线程都停止运行 等待所有线程完成后运行 我们可以使用awaitTermination()方法实现例:使用awaitTermination()方法,等待所有线程完成后运行
阻塞线程 直到所有任务完成执行或达到指定的超时 public void awaitAfterShutdown(ExecutorService threadPool) { threadPool.shutdown(); try { if (!threadPool.awaitTermination(60, TimeUnit.SECONDS)) { threadPool.shutdownNow(); } } catch (InterruptedException ex) { threadPool.shutdownNow(); Thread.currentThread().interrupt(); } }
版权声明
本文仅代表作者观点,不代表本站立场。
本文系作者授权发表,未经许可,不得转载。