Executors:提供了一系列靜態Factory 方法用於建立各種線程池。 1.Executors.newCachedThreadPool建立可變線程池
如果線程池長度超過處理需要,可靈活回收空閑線程,若無可回收,則建立線程。核心線程池大小為0,最大為Integer.MAX_VALUE,線程空閑存活時間是60秒。 範例程式碼:
ExecutorService cachedThreadPool = Executors.newCachedThreadPool(); for (int i = 1; i <= 5; i++) { final int index = i; cachedThreadPool.execute(() -> { System.out.println(index + "start"); System.out.println(Thread.currentThread().getName()); try { Thread.sleep(index * 1500); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println(index + "end"); });}
執行結果:
Executors內部建立newCachedThreadPool源碼
public static ExecutorService newCachedThreadPool() { return new ThreadPoolExecutor(0, Integer.MAX_VALUE, 60L, TimeUnit.SECONDS, new SynchronousQueue<Runnable>());}
2.Executors.newFixedThreadPool建立固定大小線程池 核心線程數即為最大線程數,線程不會被回收,直到調用shutdown方法回收 執行個體代碼:
ExecutorService fixedThreadPool = Executors.newFixedThreadPool(2);for (int i = 1; i <= 4; i++) { final int index = i; System.out.println(Thread.currentThread().getName() + "時間" + System.currentTimeMillis()); fixedThreadPool.execute(() -> { try { System.out.println(Thread.currentThread().getName() + "時間" + System.currentTimeMillis()); Thread.sleep(1500); System.out.println(Thread.currentThread().getName() + "end"); } catch (InterruptedException e) { e.printStackTrace(); } }); }
執行結果:
可以看到一直都是兩個線程執行。
Executors內部建立newFixedThreadPool源碼
public static ExecutorService newFixedThreadPool(int nThreads) { return new ThreadPoolExecutor(nThreads, nThreads, 0L, TimeUnit.MILLISECONDS, new LinkedBlockingQueue<Runnable>());}
3.Executors.newScheduledThreadPool建立定時或週期性任務執行線程池 該線程池可用於定時或週期性任務的執行
定時執行個體代碼:
ScheduledExecutorService scheduledThreadPool = Executors.newScheduledThreadPool(2); System.out.println(Thread.currentThread().getName() + "時間" + System.currentTimeMillis()); //建立線程池後3秒執行 scheduledThreadPool.schedule(() -> { System.out.println(Thread.currentThread().getName() + "時間" + System.currentTimeMillis()); System.out.println("delay 3 seconds");}, 3, TimeUnit.SECONDS);
定時執行結果:
周期執行個體代碼:
ScheduledExecutorService scheduleThreadPoolAtFixedRate = Executors.newScheduledThreadPool(5);System.out.println(Thread.currentThread().getName() + "時間" + System.currentTimeMillis());//建立線程池後1秒執行 , 之後每3秒執行一次scheduleThreadPoolAtFixedRate.scheduleAtFixedRate(() -> { System.out.println(Thread.currentThread().getName() + "時間" + System.currentTimeMillis()); System.out.println("delay 1 seconds, and excute every 3 seconds");}, 1, 3, TimeUnit.SECONDS);
周期執行結果:
Executors內部建立newScheduledThreadPool源碼
public static ScheduledExecutorService newScheduledThreadPool(int corePoolSize) { return new ScheduledThreadPoolExecutor(corePoolSize); }public ScheduledThreadPoolExecutor(int corePoolSize) { super(corePoolSize, Integer.MAX_VALUE, 0, NANOSECONDS, new DelayedWorkQueue()); }
4.Executors.singleThreadExecutor建立單線的線程池 該線程池有且僅有一個線程執行任務,保證所有任務按照指定順序(FIFO, LIFO, 優先順序)執行。
執行個體代碼:
ExecutorService singleThreadExecutor = Executors.newSingleThreadExecutor();for (int i = 1; i <= 4; i++) { final int index = i; System.out.println(Thread.currentThread().getName() + "時間" + System.currentTimeMillis()); singleThreadExecutor.execute(() -> { try { System.out.println(Thread.currentThread().getName() + "時間" + System.currentTimeMillis()); Thread.sleep(1500); System.out.println(Thread.currentThread().getName() + "end"); } catch (InterruptedException e) { e.printStackTrace(); } });}
運行結果:
Executors內部建立newSingleThreadExecutor源碼
public static ExecutorService newSingleThreadExecutor() { return new FinalizableDelegatedExecutorService (new ThreadPoolExecutor(1, 1, 0L, TimeUnit.MILLISECONDS, new LinkedBlockingQueue<Runnable>()));}
4.Executors.newWorkStealingPool建立並存執行線程池 建立一個擁有多個任務隊列(以便減少串連數)的線程池
執行個體代碼:
// 設定並行層級為2,即預設每時每刻只有2個線程同時執行 ExecutorService newWorkStealingPool = Executors.newWorkStealingPool(2); for (int i = 1; i <= 4; i++) { final int count = i; System.out.println("execute" + i); newWorkStealingPool.execute(() -> { try { Thread.sleep(1000);//此任務耗時1s System.out.println("線程" + Thread.currentThread().getName() + "完成任務:" + count + " 時間為:" + System.currentTimeMillis()); } catch (InterruptedException e) { e.printStackTrace(); } }); }
運行結果:
Executors內部建立newWorkStealingPool源碼
public static ExecutorService newWorkStealingPool(int parallelism) { return new ForkJoinPool (parallelism, ForkJoinPool.defaultForkJoinWorkerThreadFactory, null, true); }
執行個體代碼下載