B站**遇见狂神说**的视频,博客是我做的笔记,强烈推荐这个up
https://www.bilibili.com/video/BV1B7411L7tE?p=22
总结
- 三个方法()
- 七个参数(ThreadPoolExecutor的参数)
- 四大拒绝策略
线程池是池化技术的一种,我们常见的还有连接池(JDBC连接池)),对象池,内存池。池化可以系统优化资源的使用
线程池技术的优点
- 降低系统资源小号
- 提高响应速度
- 方便管理
线程服用, 可以控制最大并发数量,管理线程
三种建立线程池的方法
package com.pq.multiThread.Lock;
import java.sql.Time;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadPoolExecutor;
public class Product_Consumer {
public static void main(String[] args) throws InterruptedException {
// ExecutorService threadPool = Executors.newSingleThreadExecutor();
// ExecutorService threadPool = Executors.newCachedThreadPool();
//CPU密集型操作 固定线程池的大小等于CPU核心数量,IO密集型操作大小为核心数*2
ExecutorService threadPool = Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors());
Long t1 = System.currentTimeMillis();
for(int i=0;i<2000;i++) {
// //方法1
threadPool.submit(()->System.out.println("hhhhh "+Thread.currentThread().getName()));
//方法2
// threadPool.execute(()-> System.out.println("hhhhh "+Thread.currentThread().getName()));
}
threadPool.shutdown();
//shutDown 后线程池内的线程没执行完的继续执行,所有线程执行结束后会变为终止状态
while(!threadPool.isTerminated()) {
Thread.sleep(10);
}
System.out.println("消耗时间+"+(System.currentTimeMillis()-t1)/1000.0);
}
}
通过进入这三种方法的底层发现,他们都是用
new ThreadPoolExecutor()这种方法实现的
该方法有7个参数
这三种方法底层采用的都是defaultHandler就是(new ThreadPoolExecutor.AbortPolicy()),
单一线程池
new ThreadPoolExecutor(1, 1, 0L,
TimeUnit.MILLISECONDS,
new LinkedBlockingQueue()));
cache线程池
这个采用的是同步队列,是BlockdingQueue的一种
new ThreadPoolExecutor(0,
2147483647(这是Integer的最大值),
60L,
TimeUnit.SECONDS,
new SynchronousQueue());
}
new ThreadPoolExecutor(
nThreads,
nThreads,
0L,
TimeUnit.MILLISECONDS,
new LinkedBlockingQueue());
}
本质
public ThreadPoolExecutor(
int corePoolSize, //1 核心大小
int maximumPoolSize, //2 最大的线程池大小
long keepAliveTime, //3 超时没人使用
TimeUnit unit, //4超时时间单位
BlockingQueue<Runnable> workQueue,//5阻塞队列
ThreadFactory threadFactory, //6 线程工厂
RejectedExecutionHandler handler //7 拒绝策略
)
{
this.ctl = new AtomicInteger(ctlOf(-536870912, 0));
this.mainLock = new ReentrantLock();
this.workers = new HashSet();
this.termination = this.mainLock.newCondition();
if (corePoolSize >= 0 && maximumPoolSize > 0 && maximumPoolSize >= corePoolSize && keepAliveTime >= 0L) {
if (workQueue != null && threadFactory != null && handler != null) {
this.corePoolSize = corePoolSize;
this.maximumPoolSize = maximumPoolSize;
this.workQueue = workQueue;
this.keepAliveTime = unit.toNanos(keepAliveTime);
this.threadFactory = threadFactory;
this.handler = handler;
} else {
throw new NullPointerException();
}
} else {
throw new IllegalArgumentException();
}
}
四种拒绝策略
core + blockquee满了的时候会去探求最大线程池内赋闲的线程,如果满了就会引发拒绝策略
- 直接抛出异常
- 哪来的回哪去,不接受
- 抛弃老的
- 抛弃新来的
newFixThreadPool 阻塞队列是linked, 没有设置大小,他的拒绝策略是方法一