區域性變數Executors建立執行緒池後一定要關閉
阿新 • • 發佈:2019-01-09
參考:
http://curious.iteye.com/blog/2298849
網上有很多Executors的例子,但有些寫的非常草率,都只是寫如何建立,但有些沒有附上關閉方法。
Executors作為區域性變數時,建立了執行緒,一定要記得呼叫executor.shutdown();來關閉執行緒池,如果不關閉,會有執行緒洩漏問題。
如下有問題的程式碼:
import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; public class TestThread { public static void main(String[] args) { while (true) { try { ExecutorService service = Executors.newFixedThreadPool(1); service.submit(new Runnable() { public void run() { try { Thread.sleep(2000); } catch (InterruptedException e) { } } }); service = null; } catch (Exception e) { } try { Thread.sleep(2000); } catch (InterruptedException e) { } } } }
執行後,檢視jvm,會發現執行緒每2秒就增長一個。
加了shutdown程式碼後,就一直很平穩。
import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; public class TestThread { public static void main(String[] args) { while (true) { ExecutorService service = Executors.newFixedThreadPool(1); try { service.submit(new Runnable() { public void run() { try { Thread.sleep(2000); } catch (InterruptedException e) { } } }); } catch (Exception e) { }finally{ service.shutdown(); } try { Thread.sleep(2000); } catch (InterruptedException e) { } } } }