- 线程池
- 线程池三大方法
- 线程池七大参数
- 四种拒绝策略
使用线程池可以不用频繁的创建线程,而是复用已经创建的线程,这样可以降低开销、控制最大并发数
线程池三大方法- Executors.newSingleThreadExecutor();只包含单线程的线程池
- Executors.newFixedThreadPool(5);创建一个固定大小的线程池,线程池大小通过传入的参数设置
- Executors.newCachedThreadPool();创建一个根据需要创建新线程的线程池,但在可用时将重新使用以前构造的线程
源码
public static ExecutorService newSingleThreadExecutor() {
return new FinalizableDelegatedExecutorService
(new ThreadPoolExecutor(1, 1,
0L, TimeUnit.MILLISECONDS,
new LinkedBlockingQueue()));
}
public static ExecutorService newFixedThreadPool(int nThreads) {
return new ThreadPoolExecutor(nThreads, nThreads,
0L, TimeUnit.MILLISECONDS,
new LinkedBlockingQueue());
}
public static ExecutorService newCachedThreadPool() {
return new ThreadPoolExecutor(0, Integer.MAX_VALUE,
60L, TimeUnit.SECONDS,
new SynchronousQueue());
}
三个源码的均是通过ThreadPoolExecutor 创建线程池,看下ThreadPoolExecutor源码
public ThreadPoolExecutor(int corePoolSize,
int maximumPoolSize,
long keepAliveTime,
TimeUnit unit,
BlockingQueue 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;
}
线程池七大参数
由上述源码得知有7个参数
int corePoolSize:核心线程数 如果超过corePoolSize但小于maximumPoolSize线程运行,则仅当队列已满时才会创建一个新线程 int maximumPoolSize:最大核心线程数 long keepAliveTime:如果池当前具有多于corePoolSize线程,若有线程空闲超过keepAliveTime,则多余的线程将被终止 TimeUnit unit:超时单位 BlockingQueue四种拒绝策略workQueue:阻塞队列 1. 如果少于corePoolSize线程正在运行,Executor总是喜欢添加一个新线程,而不是排队。 2. 如果corePoolSize或更多的线程正在运行,Executor总是喜欢排队请求而不是添加一个新的线程。 3. 如果请求无法排队,则会创建一个新线程,除非这将超出maximumPoolSize,否则任务将被拒绝。 ThreadFactory threadFactory:线程工厂,创建线程使用 RejectedExecutionHandler handler:拒绝策略
提供了四个预定义的处理程序策略: 在默认ThreadPoolExecutor.AbortPolicy ,处理程序会引发运行RejectedExecutionException后排斥反应,抛出异常。
public static void main(String[] args) {
ExecutorService executorService = new ThreadPoolExecutor(
2,
5,
3,
TimeUnit.SECONDS,
new LinkedBlockingDeque<>(3),
Executors.defaultThreadFactory(),
new ThreadPoolExecutor.AbortPolicy()
);
try {
for (int i = 1; i <= 9; i++) {
executorService.execute(()->{
System.out.println(Thread.currentThread().getName()+"----ok");
});
}
}catch (Exception e){
e.printStackTrace();
}finally {
executorService.shutdown();
}
}
执行结果
pool-1-thread-2----ok
pool-1-thread-2----ok
pool-1-thread-2----ok
pool-1-thread-2----ok
pool-1-thread-1----ok
pool-1-thread-3----ok
pool-1-thread-5----ok
pool-1-thread-4----ok
java.util.concurrent.RejectedExecutionException: Task com.song.pool.Demo02$$Lambda$1/1831932724@7699a589 rejected from java.util.concurrent.ThreadPoolExecutor@58372a00[Running, pool size = 5, active threads = 4, queued tasks = 0, completed tasks = 4]
at java.util.concurrent.ThreadPoolExecutor$AbortPolicy.rejectedExecution(ThreadPoolExecutor.java:2063)
at java.util.concurrent.ThreadPoolExecutor.reject(ThreadPoolExecutor.java:830)
at java.util.concurrent.ThreadPoolExecutor.execute(ThreadPoolExecutor.java:1379)
at com.song.pool.Demo02.main(Demo02.java:23)
在ThreadPoolExecutor.CallerRunsPolicy中,调用execute本身的线程运行任务。 这提供了一个简单的反馈控制机制,将降低新任务提交的速度,哪来的回哪由调用者处理。
public static void main(String[] args) {
ExecutorService executorService = new ThreadPoolExecutor(
2,
5,
3,
TimeUnit.SECONDS,
new LinkedBlockingDeque<>(3),
Executors.defaultThreadFactory(),
new ThreadPoolExecutor.CallerRunsPolicy()
);
try {
for (int i = 1; i <= 9; i++) {
executorService.execute(()->{
System.out.println(Thread.currentThread().getName()+"----ok");
});
}
}catch (Exception e){
e.printStackTrace();
}finally {
executorService.shutdown();
}
}
执行结果
pool-1-thread-1----ok
main----ok
pool-1-thread-1----ok
pool-1-thread-5----ok
pool-1-thread-3----ok
pool-1-thread-2----ok
pool-1-thread-5----ok
pool-1-thread-1----ok
pool-1-thread-4----ok
在ThreadPoolExecutor.DiscardPolicy中 ,简单地删除无法执行的任务。
public static void main(String[] args) {
ExecutorService executorService = new ThreadPoolExecutor(
2,
5,
3,
TimeUnit.SECONDS,
new LinkedBlockingDeque<>(3),
Executors.defaultThreadFactory(),
new ThreadPoolExecutor.DiscardPolicy()
);
try {
for (int i = 1; i <= 9; i++) {
executorService.execute(()->{
System.out.println(Thread.currentThread().getName()+"----ok");
});
}
}catch (Exception e){
e.printStackTrace();
}finally {
executorService.shutdown();
}
}
执行结果
pool-1-thread-1----ok
pool-1-thread-4----ok
pool-1-thread-1----ok
pool-1-thread-3----ok
pool-1-thread-2----ok
pool-1-thread-1----ok
pool-1-thread-4----ok
pool-1-thread-5----ok
在ThreadPoolExecutor.DiscardOldestPolicy中 ,如果执行程序没有关闭,则工作队列头部的任务被删除,然后重试执行(可能会再次失败,导致重复)
public static void main(String[] args) {
ExecutorService executorService = new ThreadPoolExecutor(
2,
5,
3,
TimeUnit.SECONDS,
new LinkedBlockingDeque<>(3),
Executors.defaultThreadFactory(),
new ThreadPoolExecutor.DiscardOldestPolicy()
);
try {
for (int i = 1; i <= 9; i++) {
executorService.execute(()->{
System.out.println(Thread.currentThread().getName()+"----ok");
});
}
}catch (Exception e){
e.printStackTrace();
}finally {
executorService.shutdown();
}
}
执行结果
pool-1-thread-1----ok
pool-1-thread-2----ok
pool-1-thread-3----ok
pool-1-thread-3----ok
pool-1-thread-4----ok
pool-1-thread-5----ok
pool-1-thread-3----ok
pool-1-thread-1----ok
pool-1-thread-4----ok



