1. 程式人生 > >執行緒池 ThreadPoolExecutor 總結

執行緒池 ThreadPoolExecutor 總結

package com.sky.test;

import java.util.concurrent.*;

/**
 * 執行緒池測試
 * @author QZJ on 2018/10/28.
 */
public class ThreadPoolTest {

    public static void main(String[] args) {
        testThreadPool();
//        testNormalThreadPool();
    }

    private static void testThreadPool() {
        //ThreadPoolExecutor 說明
        //corePoolSize: 當任務條數 <= corePoolSize,建立執行緒
        //workQueue: 總任務數, 若當前執行緒數完全可以處理workQueue的任務,則workQueue佇列不會滿。
        //maximumPoolSize: 當workQueue佇列滿時,並且 maximumPoolSize > 當任務條數 >= corePoolSize, 建立新的執行緒
        //keepAliveTime: 當有空閒執行緒,超過aliveTime,回收
        //allowCoreThreadTimeOut: 設定為true,這表示corePoolSize中的執行緒,在空閒時也可回收
        //RejectedExecutionHandler: 新增任務,進行資源判斷,能否接受任務(既滿足以上條件),不能則丟擲RejectedExecutionException異常
        //tip: 當丟擲RejectedExecutionException異常, 執行緒池仍處於可用狀態,並未shutdown,視情況是否需要捕獲異常
ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(5,10, 1, TimeUnit.MILLISECONDS, new LinkedBlockingQueue<>(), Executors.defaultThreadFactory()); while (true) { try { Thread.sleep(1000L); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println("---------"+threadPoolExecutor.getQueue().size()+","+threadPoolExecutor.getTaskCount()); if (threadPoolExecutor.getQueue().size() == 0) { for (int i=0;i<20;i++) { try { threadPoolExecutor.execute(new MyRunnable(i+"ThreadPoolExecutor******")); } catch (Exception e) { System.out.println("exception->"+i+"ThreadPoolExecutor******"); } } } } } private static void testNormalThreadPool(){ //執行緒建立底層均使用的ThreadPoolExecutor //定時執行 + 執行緒池 ScheduledThreadPoolExecutor scheduledThreadPoolExecutor = new ScheduledThreadPoolExecutor(2); scheduledThreadPoolExecutor.scheduleAtFixedRate(() -> System.out.println("scheduledThreadPoolExecutor"), 0, 1, TimeUnit.SECONDS); scheduledThreadPoolExecutor.shutdown(); //固定執行緒數 ExecutorService newFixedThreadPool = Executors.newFixedThreadPool(10); for (int i=0;i<12;i++) { newFixedThreadPool.execute(new MyRunnable(i+"msg")); } newFixedThreadPool.shutdown(); //單例執行緒 單執行緒 ExecutorService newSingleThreadExecutor = Executors.newSingleThreadExecutor(); for (int i=0;i<12;i++) { newSingleThreadExecutor.execute(new MyRunnable("qzj"+i)); } newSingleThreadExecutor.shutdown(); //可快取執行緒池 無限制,較靈活 ExecutorService newCachedThreadPool = Executors.newCachedThreadPool(); newCachedThreadPool.execute(new Runnable() { @Override public void run() { System.out.println("newCachedThreadPool"); } }); } public static class MyRunnable implements Runnable { private String msg; public MyRunnable(String msg) { this.msg = msg; } @Override public void run() { try { Thread.sleep(2000); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println(msg); } } }