ExecutorService threadPool = Executors.newFixedThreadPool(5);
public static ExecutorService newFixedThreadPool(int nThreads) { return new ThreadPoolExecutor(nThreads, nThreads, 0L, TimeUnit.MILLISECONDS, new LinkedBlockingQueue<Runnable>()); }
public ThreadPoolExecutor(int corePoolSize, int maximumPoolSize, long keepAliveTime, TimeUnit unit, BlockingQueue<Runnable> workQueue) { this(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue, Executors.defaultThreadFactory(), defaultHandler); }
public ThreadPoolExecutor(int corePoolSize, int maximumPoolSize, long keepAliveTime, TimeUnit unit, BlockingQueue<Runnable> workQueue, ThreadFactory threadFactory, RejectedExecutionHandler handler) { if (corePoolSize < 0 || maximumPoolSize <= 0 || maximumPoolSize < corePoolSize || keepAliveTime < 0) throw new IllegalArgumentException(); if (workQueue == null || threadFactory == null || handler == null) throw new NullPointerException(); this.acc = System.getSecurityManager() == null ? null : AccessController.getContext(); this.corePoolSize = corePoolSize; this.maximumPoolSize = maximumPoolSize; this.workQueue = workQueue; this.keepAliveTime = unit.toNanos(keepAliveTime); this.threadFactory = threadFactory; this.handler = handler; }
- corePoolSize:線程池中常駐核心線程數
- maximumPoolSize:線程池能夠容納同時執行的最大線程數,此值必須大於等於1,讀音[ˈmæksɪməm]咩西門-最大限度
- keepAliveTime:多余的空閑線程存活時間。當前線程池數量超過corePoolSize時,當空閑時間到達keepAliveTime值時,多余空閑線程會被銷毀直到只剩下corePoolSize個線程為止。
- unit:keepAliveTime的時間單位
- workQueue:任務隊列,被提交但尚未執行的任務
- threadFactory:表示生成線程池中的工作線程的線程工廠,用於創建線程,一般為默認線程工廠即可
- handler:拒絕策略,表示當隊列滿了並且工作線程大於等於線程池的最大線程數(maximumPoolSize)時如何來拒絕來請求的Runnable的策略