在 Java
中和關閉線程池相關的方法主要有以下:java
void shutdown()
List<Runnable> shutDownNow
boolean awaitTermination
boolean isShutDown
boolean isTerminated
shutDown
方法從字面意思咱們能夠看到是中止關閉的意思,咱們先來看下面的一段代碼,首先咱們經過 ThreadPoolExecutor
來建立一個容量是10的無界線程池,與 FixedThreadPool
相似的,這裏手動建立能夠更好地理解線程池的建立。在後咱們提交一千個任務執行,再執行 shutdown
方法進行暫停。public static void main(String[] args) throws InterruptedException { ExecutorService service = new ThreadPoolExecutor( 10, 10, 0L, TimeUnit.MILLISECONDS, new LinkedBlockingQueue<>()); for (int i = 0; i < 1000; i++) { service.submit(() ->{ try { TimeUnit.SECONDS.sleep(1); } catch (InterruptedException e) { System.out.println("接受中斷,不處理~~"); } System.out.println("args = " + Arrays.deepToString(args)+ Thread.currentThread().getName()); }); } service.shutdown(); }
ShutDown
而言它能夠安全的中止一個線程池,它有幾個關鍵點ShutDown
會首先將線程設置成 SHUTDOWN
狀態,而後中斷全部沒有正在運行的線程shutDown
方法其實就是要等待全部任務正常所有結束之後纔會關閉線程池shutdown()
方法後若是還有新的任務被提交,線程池則會根據拒絕策略直接拒絕後續新提交的任務。now
,即當即中止任務,public static void main(String[] args) throws InterruptedException { ExecutorService service = new ThreadPoolExecutor( 10, 10, 0L, TimeUnit.MILLISECONDS, new LinkedBlockingQueue<>(1000)); for (int i = 0; i < 1000; i++) { service.submit(() ->{ try { TimeUnit.SECONDS.sleep(1); } catch (InterruptedException e) { System.out.println("接受中斷,結束線程~~"); //這裏響應中斷 return; } System.out.println("args = " + Arrays.deepToString(args)+ Thread.currentThread().getName()); }); } final List<Runnable> runnables = service.shutdownNow(); System.out.println(runnables); }
shutDownNow
方法後,會像所有正在運行的隊列通知中斷,正在運行的線程接收到中斷信號後選擇處理,而在隊列中的所有取消執行轉移到一個list
隊列中返回,如上述 List<Runnable> runnables
,這裏記錄了全部終止的線程boolean awaitTermination_(_long timeout, TimeUnit unit_)_
timeout
表示等待的時間,unit
時間單位timeout
時間後,反饋線程池的狀態,true
;false
;isShutDown
方法正如名字,判斷線程池是否中止,返回的是 Boolean
類型,若是已經開始中止線程池則返回 true
不然放回falseshutDown
或shutDownNow
時以後,會返回 true
不過須要注意,這時候只是表明線程池關閉流程的開始,並非說線程池已經中止了shutdown
方法以後,線程池會繼續執行裏面未完成的任務,包括正在執行的任務和在任務隊列中等待的任務。shutdown
方法,可是有一個線程依然在執行任務,那麼此時調用 isShutdown
方法返回的是 true
,而調用 isTerminated
方法返回的即是 false
,由於線程池中還有任務正在在被執行,線程池並無真正「終結」。isTerminated()
方法纔會返回 true
,這表示線程池已關閉而且線程池內部是空的,全部剩餘的任務都執行完畢了。本文由AnonyStar 發佈,可轉載但需聲明原文出處。
歡迎關注微信公帳號 :雲棲簡碼 獲取更多優質文章
更多文章關注筆者博客 : 雲棲簡碼 i-code.online