先来看这个Executors来创建线程池:
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class ExecutorsDemo {
public static void main(String[] args) {
// ExecutorService service = Executors.newSingleThreadExecutor();//单个线层
// ExecutorService service = Executors.newFixedThreadPool(5); //五个线程
ExecutorService service = Executors.newCachedThreadPool();//弹性线程,会自己去判断创造几个
try {
for (int i = 1; i <10 ; i++) {
service.execute(()->{
System.out.println(Thread.currentThread().getName());
});
}
} catch (Exception e) {
e.printStackTrace();
} finally {
service.shutdown();
}
}
}
三大方法的底层源码:观察后可以发现,这三个底层源码都是传入了参数,例如单线程的就是(1,1)多线程的则传入对应线程数,变化线程的就传入(0,最大数)。
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,
60L, TimeUnit.SECONDS,
new SynchronousQueue<Runnable>());
}
进入最底层原码发现:
public ThreadPoolExecutor(int corePoolSize, //线程池初始大小,最少开几个线程
int maximumPoolSize, //最大线程池大小 ,最多开多少
long keepAliveTime,//最大线程池空闲时间,空闲太久级把大于 初始大小的线程释放
TimeUnit unit, //超时的单位
BlockingQueue<Runnable> workQueue) { //阻塞队列
this(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue, Executors.defaultThreadFactory(), //线程工厂,默认不动
defaultHandler); //拒绝策略
}
所以最底层其实是要填写7大参数的,我们试着来写一个自己的线程池:
import java.util.concurrent.*;
public class ExecutorsDemo {
public static void main(String[] args) {
// ExecutorService service = Executors.newSingleThreadExecutor();//单个线层
// ExecutorService service = Executors.newFixedThreadPool(5); //五个线程
// ExecutorService service = Executors.newCachedThreadPool();//弹性线程,会自己去判断创造几个
ThreadPoolExecutor service = new ThreadPoolExecutor(
2,
5,
3,
TimeUnit.SECONDS,
new LinkedBlockingDeque<>(3),
Executors.defaultThreadFactory(),
new ThreadPoolExecutor.AbortPolicy()
//几个后拒绝是看LinkedBlockingDeque+max
);
try {
for (int i = 1; i <=10 ; i++) {
service.execute(()->{
System.out.println(Thread.currentThread().getName());
});
}
} catch (Exception e) {
e.printStackTrace();
} finally {
service.shutdown();
}
}
}
当,我们调用的线程for里的循环超过9以后,则出现拒绝策略:
pool-1-thread-1
pool-1-thread-2
pool-1-thread-1
pool-1-thread-2
pool-1-thread-1
pool-1-thread-3
pool-1-thread-4
pool-1-thread-5
java.util.concurrent.RejectedExecutionException: Task ExecutorsDemo$$Lambda$1/1078694789@3b9a45b3 rejected from java.util.concurrent.ThreadPoolExecutor@7699a589[Running, pool size = 5, active threads = 3, queued tasks = 0, completed tasks = 5]
at java.util.concurrent.ThreadPoolExecutor$AbortPolicy.rejectedExecution(ThreadPoolExecutor.java:2047)
at java.util.concurrent.ThreadPoolExecutor.reject(ThreadPoolExecutor.java:823)
at java.util.concurrent.ThreadPoolExecutor.execute(ThreadPoolExecutor.java:1369)
at ExecutorsDemo.main(ExecutorsDemo.java:20)
Process finished with exit code 0
继续翻看源码:可以看到,我们的拒绝策略一共有四个,
四个拒绝策略:
new ThreadPoolExecutor.AbortPolicy() //超出后抛出异常
new ThreadPoolExecutor.CallerRunsPolicy()//超出后,超出的线程原本是谁的,谁就去执行
new ThreadPoolExecutor.DiscardOldestPolicy()//新方法,会去尝试获取线程,获取不到则直接拒绝不返回错误
new ThreadPoolExecutor.DiscardPolicy() //直接拒绝不返回错误
至此,自定义线程池完毕