一、为什么用线程池:
- 降低系统资源的消耗,通过重用已经存在的线程,降低线程创建和销毁所带来的消耗
- 提高系统的响应速度,任务到达时,不必等待新线程的创建就可以立即执行
- 方便线程并发数量的管控。放任线程的无限制创建,会额外的消耗系统资源
二、ThreadPoolExecutor 构造方法参数
corePoolSize: 线程池里面核心线程数
maximumPoolSize:线程池中最大的线程数
keepAliveTime: 想成池中的线程没有任务执行的时候会存活多久
workQueue:堵塞队列
三、常用的线程池
2.1 newCachedThreadPoll
创建一个可以缓存的线程池,线程池的长度超过处理需要,就会灵活的回收空闲线程,若无可回收的,则创建新线程
/**
* 0个核心线程
* 可以创建无限个线程
* 60L之后未使用,销毁
* SynchronousQueue 队列
**/
public static ExecutorService newCachedThreadPool() {
return new ThreadPoolExecutor(0, Integer.MAX_VALUE,
60L, TimeUnit.SECONDS,
new SynchronousQueue<Runnable>());
}
2.2 newFixedThreadPoll
创建一个定长的线程池,可以控制线程最大并发数,超出的线程会在队列中等待
/**
* nThreads个核心线程
* 可以创建nThreads个线程
* 0L之后未使用,销毁
* LinkedBlockingQueue 队列
**/
public static ExecutorService newFixedThreadPool(int nThreads) {
return new ThreadPoolExecutor(nThreads, nThreads,
0L, TimeUnit.MILLISECONDS,
new LinkedBlockingQueue<Runnable>());
}
2.3 newScheduleThreadPoll
创建一个定长的线程池,支持定期及周期性任务执行
public static ScheduledExecutorService newScheduledThreadPool(int corePoolSize) {
return new ScheduledThreadPoolExecutor(corePoolSize);
}
public ScheduledThreadPoolExecutor(int corePoolSize) {
super(corePoolSize, Integer.MAX_VALUE, 0, NANOSECONDS,
new DelayedWorkQueue());
}
2.4 newSingleThreadExecutor
创建一个单线程化的线程池,保证所有的任务按照制定的顺序执行
public static ExecutorService newSingleThreadExecutor() {
return new FinalizableDelegatedExecutorService
(new ThreadPoolExecutor(1, 1,
0L, TimeUnit.MILLISECONDS,
new LinkedBlockingQueue<Runnable>()));
}
四、提交优先级
核心线程—队列----其他
代码:
// execute 方法
int c = ctl.get();
// 核心线程是否已满
if (workerCountOf(c) < corePoolSize) {
if (addWorker(command, true))
return;
c = ctl.get();
}
// 线程池运行中 && 队列是否满了
if (isRunning(c) && workQueue.offer(command)) {
int recheck = ctl.get();
if (! isRunning(recheck) && remove(command))
reject(command);
else if (workerCountOf(recheck) == 0)
addWorker(null, false);
}
// 非核心线程
else if (!addWorker(command, false))
reject(command);