Java ExcutorService優(yōu)雅關(guān)閉方式解析
關(guān)閉時可使用如下代碼
public static void waitUntilTerminate(final ExecutorService executorService, final int timeout) { try { executorService.shutdown(); if (!executorService.awaitTermination(timeout, TimeUnit.SECONDS)) { //超時后直接關(guān)閉 executorService.shutdownNow(); } } catch (InterruptedException e) { //awaitTermination 出現(xiàn)中斷異常也將觸發(fā)關(guān)閉 executorService.shutdownNow(); } }
但是實際使用中,可能會出現(xiàn)即使使用了shutdownNow方法,還是無法終止線程的問題,那是因為你的線程無法被中斷
shutdownNow方法簡單理解就是給在運行的線程發(fā)一個中斷信號,如果你的線程忽略這個信號,那就無法停下來
舉個例子來說明這個問題
public class ShutDownUtilsTest { private ExecutorService executorService; @Before public void init() { executorService = Executors.newFixedThreadPool(1); } @Test public void shutDownOKTest() { ShutDownUtils.waitUntilTerminate(executorService, 1); CommonUtils.sleep(1); //等待線程處理中斷 Assert.assertTrue(executorService.isTerminated()); } @Test public void shutDownNowFailTest() { executorService.execute(this::canNotStopThread); ShutDownUtils.waitUntilTerminate(executorService, 0); CommonUtils.sleep(1); //等待線程處理中斷 Assert.assertFalse(executorService.isTerminated()); } @Test public void shutDownNowOKTest() { executorService.execute(this::stopThread); ShutDownUtils.waitUntilTerminate(executorService, 0); CommonUtils.sleep(1); //等待線程處理中斷 Assert.assertTrue(executorService.isTerminated()); } private void canNotStopThread() { for (long i = 0; i < Long.MAX_VALUE; i++) { } } private void stopThread() { for (long i = 0; i < Long.MAX_VALUE && !Thread.currentThread().isInterrupted(); i++) { } } }
從上面的測試用例可以看到canNotStopThread無法被shutDownNow終止
然而stopThread可以被正常終止,因為通過Thread.currentThread().isInterrupted()在判斷線程是否收到了中斷信號
以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
python?pandas創(chuàng)建多層索引MultiIndex的6種方式
這篇文章主要為大家介紹了python?pandas創(chuàng)建多層索引MultiIndex的6種方式,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2022-07-07使用TensorFlow搭建一個全連接神經(jīng)網(wǎng)絡(luò)教程
今天小編就為大家分享一篇使用TensorFlow搭建一個全連接神經(jīng)網(wǎng)絡(luò)教程,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2020-02-02Caffe數(shù)據(jù)可視化環(huán)境python接口配置教程示例
這篇文章主要為大家介紹了Caffe數(shù)據(jù)可視化環(huán)境python接口配置教程示例詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2022-06-06Python Pytorch深度學(xué)習(xí)之神經(jīng)網(wǎng)絡(luò)
今天小編就為大家分享一篇關(guān)于Pytorch神經(jīng)網(wǎng)絡(luò)的文章,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2021-10-10