問題:
關閉 Java 時如何確保正在執行的任務終止任務?
答案:
ExecutorService 的Oracle API 文件建議使用以下方法:
<code class="java">void shutdownAndAwaitTermination(ExecutorService pool) { pool.shutdown(); // Disable new tasks try { // Wait for existing tasks if (!pool.awaitTermination(60, TimeUnit.SECONDS)) { pool.shutdownNow(); // Cancel executing tasks if (!pool.awaitTermination(60, TimeUnit.SECONDS)) System.err.println("Pool did not terminate"); } } catch (InterruptedException ie) { pool.shutdownNow(); Thread.currentThread().interrupt(); } }</code>
關閉相關方法:
awaitTermination: 阻塞,直到所有任務完成或發生逾時或中斷。
<code class="java">if (!pool.awaitTermination(60, TimeUnit.SECONDS))</code>
<code class="java">while (!pool.awaitTermination(60, TimeUnit.SECONDS))</code>
以上是Java ExecutorService關閉時如何確保任務終止?的詳細內容。更多資訊請關注PHP中文網其他相關文章!