池化技术:
程序运行就是资源的占用,池化就是优化资源利用,线程池,连接池啥的,创建销毁很耗费时间空间,所以就提前准备好资源,你来那就行,用完换回来。
减少资源消耗,速度提升,还有或就是方便管理,线程复用,就像sqlsession一样,查出数据存着,可控制最大并发
三大方法:(不建议使用)
package com.qcby.lock;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
/**
* @author HuangHaiyang
* @date 2020/07/07
* @description: description
* @version: 1.0.0
*/
public class ThreadPoolTest {
public static void main(String[] args) {
//单个线程
ExecutorService threadPool = Executors.newSingleThreadExecutor();
// 创建一个固定的线程池的大小
ExecutorService threadPool1 = Executors.newFixedThreadPool(5);
//可伸缩的,遇强则强,遇弱则弱
ExecutorService threadPool2 = Executors.newCachedThreadPool();
try {
for (int i = 1; i <=100 ; i++) {
// threadPool.execute(()->{
// System.out.println(Thread.currentThread().getName()+"-------->OK");
// });
// threadPool1.execute(()->{
// System.out.println(Thread.currentThread().getName()+"-------->OK");
// });
threadPool2.execute(()->{
System.out.println(Thread.currentThread().getName()+"-------->OK");
});
}
} catch (Exception e) {
e.printStackTrace();
} finally {
threadPool.shutdown();
threadPool1.shutdown();
threadPool2.shutdown();
}
}
}
七大参数
去读上面三个方法的源码,可以看到他们的本质都是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;
}
package com.qcby.lock;
import java.util.concurrent.*;
/**
* @author HuangHaiyang
* @date 2020/07/07
* @description: description
* @version: 1.0.0
*/
public class ThreadPoolTest {
public static void main(String[] args) {
ThreadPoolExecutor poolExecutor = new ThreadPoolExecutor(
2,//核心线程2个
5,//最大线程5个
3,//3秒没人就断开,只留核心线程
TimeUnit.SECONDS,//时间单位
new LinkedBlockingDeque<>(5),//阻塞队列,相当于候客区
Executors.defaultThreadFactory(),//默认线程工程
new ThreadPoolExecutor.AbortPolicy()//默认拒绝策略,例如:银行满了,还有人进来,不处理这个人,抛出异常
);
try {
for (int i = 1; i <=10 ; i++) {
poolExecutor.execute(()->{
System.out.println(Thread.currentThread().getName()+"-------->OK");
});
}
} catch (Exception e) {
e.printStackTrace();
} finally {
poolExecutor.shutdown();
}
}
}
jdk1.8中提供的四种拒绝策略
/**
* new ThreadPoolExecutor.AbortPolicy() // 银行满了,还有人进来,不处理这个人的,抛出异常
* new ThreadPoolExecutor.CallerRunsPolicy() // 哪来的去哪里!
* new ThreadPoolExecutor.DiscardPolicy() //队列满了,丢掉任务,不会抛出异常!
* new ThreadPoolExecutor.DiscardOldestPolicy() //队列满了,尝试去和最早的竞争,也不会抛出异常!
*/