上图为线程池的处理流程原理。
提交任务有两种,执行execute和sumbit有返回future对象
Executor:是Java线程池的顶级接口
Executors:是一个类,提供了不同的静态方法。用于生成不同类型的线程池。
ThreadPoolExecutor的七个参数:
1.核心线程池的大小
2.最大线程池的大小
3.线程大于核心线程时。空闲任务等待分配任务的最长时间
4.这个时间的度量单位
5.保存任务的工作队列 不同线程池使用不同的阻塞队列
6.线程工厂
7.饱和策略
Executors产生的几种线程池
1.固定大小的线程池
newFixedThreadPool
public static ExecutorService newFixedThreadPool(int nThreads) {
return new ThreadPoolExecutor(nThreads, nThreads,
0L, TimeUnit.MILLISECONDS,
new LinkedBlockingQueue<Runnable>());
}
2.单线程的线程池
public static ExecutorService newSingleThreadExecutor() {
return new FinalizableDelegatedExecutorService
(new ThreadPoolExecutor(1, 1,
0L, TimeUnit.MILLISECONDS,
new LinkedBlockingQueue<Runnable>()));
}
3.大小可变无界的线程池
public static ExecutorService newCachedThreadPool(ThreadFactory threadFactory) {
return new ThreadPoolExecutor(0, Integer.MAX_VALUE,
60L, TimeUnit.SECONDS,
new SynchronousQueue<Runnable>(),
threadFactory);
}
4.可延迟的线程池
public ScheduledThreadPoolExecutor(int corePoolSize,
ThreadFactory threadFactory) {
super(corePoolSize, Integer.MAX_VALUE, 0, TimeUnit.NANOSECONDS,
new DelayedWorkQueue(), threadFactory);
}
J.U.C包中几种BlockingQueue队列:
1.ArrayBlockingQueue:
数组支持的有界队列,按照先进先出的顺序排列。需指定最大容量和是否为公平锁。不会自己扩容,默认非公平锁。
2.DelayQueue:ScheduledThreadPoolExecutor
是一个无界阻塞队列,只有延期满了才能从中提取元素。(支付项目)
3.LinkedBlockingDeque:
一个阻塞双端队列,可指定容量
4.LinkedBlockinQueue newSingleThreadExecutor newFixedThreadPool
一个基于链表的阻塞队列,吞吐量要低于ArrayBlockingQueue
5.PriorityBlockingQueue:
一个无界阻塞队列。逻辑上无界,资源耗尽 add也会失败 不允许null
6.sysnchronousQueue: newCachedThreadPool
一种阻塞队列,每个插入必须等待另一个线程对应的移除。