学习过程观看视频:[狂神说Java]
https://www.bilibili.com/video/BV1B7411L7tE?p=13
欢迎大家支持噢,很良心的老师了!
线程池三种创建方式源码
实际都是通过创建ThreadPoolExecutor来创建线程池
public static ExecutorService newSingleThreadExecutor() {
return new FinalizableDelegatedExecutorService
(new ThreadPoolExecutor(1, 1,
0L, TimeUnit.MILLISECONDS,
new LinkedBlockingQueue<Runnable>()));
}
public static ExecutorService newFixedThreadPool(int nThreads) {
return new ThreadPoolExecutor(nThreads, nThreads,
0L, TimeUnit.MILLISECONDS,
new LinkedBlockingQueue<Runnable>());
}
public static ExecutorService newCachedThreadPool() {
return new ThreadPoolExecutor(0, Integer.MAX_VALUE, //21亿,导致OOM
60L, TimeUnit.SECONDS,
new SynchronousQueue<Runnable>());
}
创建ThreadPoolExecutor源码
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;
}
手动创建一个线程池
java代码
package com.add;
import java.util.concurrent.*;
/**
* Created by zjl
* 2020/11/25
**/
/*** new ThreadPoolExecutor.AbortPolicy() // 银行满了,还有人进来,不处理这个人的,抛出异 常
* * new ThreadPoolExecutor.CallerRunsPolicy() // 哪来的去哪里!
* * new ThreadPoolExecutor.DiscardPolicy() //队列满了,丢掉任务,不会抛出异常!
* * new ThreadPoolExecutor.DiscardOldestPolicy() //队列满了,尝试去和最早的竞争,也不会 抛出异常!
* */
public class ExecutorsTest2 {
public static void main(String[] args) {
//自定义线程池
ExecutorService threadPool = new ThreadPoolExecutor(
2, //核心线程数
7, //核心最大线程数
1, //超时时间 1s,超过1秒没人使用,会断开线程
TimeUnit.SECONDS, //超时单位 s
new LinkedBlockingDeque<>(3), //阻塞队列 大小设置3
Executors.defaultThreadFactory(), // 线程工厂:创建线程的,一般不用动
new ThreadPoolExecutor.AbortPolicy() //拒绝策略
);
try {
for (int i = 1; i <= 2; i++) {
threadPool.execute(()->{
System.out.println(Thread.currentThread().getName());
});
}
} catch (Exception e) {
e.printStackTrace();
} finally {
threadPool.shutdown();
}
}
}
当for循环的次数设置为2的时候:
此时核心线程数足够使用。
当for循环的次数设置为4的时候:
此时核心线程数不够使用,但是只多出2条线程,阻塞队列的大小为3,足够存放多出来的这2条线程,所以还是只有两条线程在跑。
当for循环的次数设置为6的时候:
此时核心线程数不够使用,多出4条线程,阻塞队列的大小为3,不足以存放多出来的这4条线程,所以不止两个线程在跑。
当for循环的次数设置为19的时候:
最大承载量是 最大线程数 + 阻塞队列数 = 7+3 =10
此时已经超过最大承载量,此种拒绝策略会报拒绝执行异常。
pool-1-thread-1
pool-1-thread-3
pool-1-thread-2
pool-1-thread-3
pool-1-thread-4
pool-1-thread-2
pool-1-thread-1
pool-1-thread-2
pool-1-thread-5
pool-1-thread-4
pool-1-thread-4
pool-1-thread-3
pool-1-thread-4
pool-1-thread-7
pool-1-thread-5
pool-1-thread-2
pool-1-thread-6
pool-1-thread-1
java.util.concurrent.RejectedExecutionException: Task com.add.ExecutorsTest2$$Lambda$1/668386784@10f87f48 rejected from java.util.concurrent.ThreadPoolExecutor@b4c966a[Running, pool size = 7, active threads = 3, queued tasks = 0, completed tasks = 15]
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.add.ExecutorsTest2.main(ExecutorsTest2.java:30)
Process finished with exit code 0