池化技术
线程的运行,本质:占用系统的资源!优化资源的使用!=> 池化技术
线程池 连接池 内存池 对象池
池化技术:事先准备好一些资源,使用拿走,不使用还给我。
线程池的好处:
1.降低资源的消耗
2.提高响应的速度
3.方便管理
线程复用,可以控制最大并发数,管理线程
线程池三大方法
public class PoolTest1 {
public static void main(String[] args) {
//ExecutorService pool = Executors.newSingleThreadExecutor();//单个线程池
//ExecutorService pool = Executors.newFixedThreadPool(5);//固定线程池
ExecutorService pool = Executors.newCachedThreadPool();//缓存 可伸缩
try {
for (int i = 0; i < 10; i++) {
pool.execute(()->{
System.out.println(Thread.currentThread().getName());
});
}
} catch (Exception e) {
e.getStackTrace();
} finally {
//需要关闭
pool.shutdown();
}
}
}
Executors.newSingleThreadExecutor()单个线程池
Executors.newFixedThreadPool(5)固定线程池
Executors.newCachedThreadPool()缓存 可伸缩
7大参数
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>());
}
他们其实调用的都是创建了一个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.corePoolSize = corePoolSize;
this.maximumPoolSize = maximumPoolSize;
this.workQueue = workQueue;
this.keepAliveTime = unit.toNanos(keepAliveTime);
this.threadFactory = threadFactory;
this.handler = handler;
}
int corePoolSize, //核心线程大小
int maximumPoolSize, //最大线程大小
long keepAliveTime, //超时释放时间
TimeUnit unit, //超时单位
BlockingQueue workQueue, //阻塞队列
ThreadFactory threadFactory, //线程工程(一般不动)
RejectedExecutionHandler handler //拒绝策略
四种拒绝策略
public static void main(String[] args) {
ThreadPoolExecutor poolExecutor = new ThreadPoolExecutor(
2,
5,
2,
TimeUnit.SECONDS,
new LinkedBlockingDeque<>(3),
Executors.defaultThreadFactory(),
new ThreadPoolExecutor.AbortPolicy()
);
try {
//最大承载 Deque + max
for (int i = 1; i <= 10; i++) {
poolExecutor.execute(()->{
System.out.println(Thread.currentThread().getName());
});
}
} catch (Exception e) {
e.getStackTrace();
} finally {
poolExecutor.shutdown();
}
}
当线程池的任务缓存队列已满并且线程池中的线程数目达到maximumPoolSize时,如果还有任务到来就会采取任务拒绝策略