JDK1.8 建立執行緒池有哪幾種方式?
阿新 • • 發佈:2021-08-29
newFixedThreadPool
定長執行緒池,每當提交一個任務就建立一個執行緒,直到達到執行緒池的最大數量,這時執行緒數量不再變化,當執行緒發生錯誤結束時,執行緒池會補充一個新的執行緒
測試程式碼:
public class TestThreadPool { //定長執行緒池,每當提交一個任務就建立一個執行緒,直到達到執行緒池的最大數量,這時執行緒數量不再變化,當執行緒發生錯誤結束時,執行緒池會補充一個新的執行緒 static ExecutorService fixedExecutor = Executors.newFixedThreadPool(3); public staticView Codevoid main(String[] args) { testFixedExecutor(); } //測試定長執行緒池,執行緒池的容量為3,提交6個任務,根據列印結果可以看出先執行前3個任務,3個任務結束後再執行後面的任務 private static void testFixedExecutor() { for (int i = 0; i < 6; i++) { final int index = i; fixedExecutor.execute(new Runnable() { public void run() { try { Thread.sleep(3000); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println(Thread.currentThread().getName() + " index:" + index); } }); } try { Thread.sleep(4000); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println("4秒後..."); fixedExecutor.shutdown(); } }
列印結果:
pool-1-thread-1 index:0 pool-1-thread-2 index:1 pool-1-thread-3 index:2 4秒後... pool-1-thread-3 index:5 pool-1-thread-1 index:3 pool-1-thread-2 index:4
- newCachedThreadPool
可快取的執行緒池,如果執行緒池的容量超過了任務數,自動回收空閒執行緒,任務增加時可以自動新增新執行緒,執行緒池的容量不限制
public class TestThreadPool { //可快取的執行緒池,如果執行緒池的容量超過了任務數,自動回收空閒執行緒,任務增加時可以自動新增新執行緒,執行緒池的容量不限制 static ExecutorService cachedExecutor = Executors.newCachedThreadPool(); public static void main(String[] args) { testCachedExecutor(); } //測試可快取執行緒池 private static void testCachedExecutor() { for (int i = 0; i < 6; i++) { final int index = i; cachedExecutor.execute(new Runnable() { public void run() { try { Thread.sleep(3000); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println(Thread.currentThread().getName() + " index:" + index); } }); } try { Thread.sleep(4000); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println("4秒後..."); cachedExecutor.shutdown(); } }View Code
列印結果:
pool-1-thread-1 index:0 pool-1-thread-6 index:5 pool-1-thread-5 index:4 pool-1-thread-4 index:3 pool-1-thread-3 index:2 pool-1-thread-2 index:1 4秒後...
https://mp.weixin.qq.com/s/_x8tCnGl7FbQiTKrHTUMWw
故鄉明