线程池
线程池:三大方法,七大参数,四种拒绝策略
池化技术
程序运行的本质:占用系统资源!优化资源的使用===>池化技术
线程池、连接池、对象池、内存池。。。。。创建、销毁十分浪费资源
- 池化技术:先创建好一些资源,有人要用,就来我这里拿。用完之后还给我
线程池的好处:
- 降低资源消耗
- 提高响应速度
- 方便管理
线程复用、控制最大并发数、管理线程
三大方法
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
/**
* @Description Executors 工具类,三大方法
* @Author cai feifei
*/
public class Test {
public static void main(String[] args) {
//单个线程
//ExecutorService threadPools = Executors.newSingleThreadExecutor();
//指定线程池数量
//ExecutorService threadPools = Executors.newFixedThreadPool(5);
//遇强则强,遇弱则弱,可以伸缩
ExecutorService threadPools = Executors.newCachedThreadPool();
try {
for(int i=0;i<100;i++){
//使用线程池后,用线程池来创建线程
threadPools.execute(()->{
System.out.println(Thread.currentThread().getName()+"======");
});
}
} catch (Exception e) {
e.printStackTrace();
} finally {
//线程池的线程使用后,一定要关闭
threadPools.shutdown();
}
}
}
七大参数
newSingleThreadExecutor()、newFixedThreadPool()、newCachedThreadPool()
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.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;
}
四种拒绝策略
- 四种拒绝策略
- AbortPolicy:线程池满了,等待区(阻塞队列也满了)抛出异常:Task com.fly.juc.pool.Test$$Lambda$1/558638686@568db2f2 rejected from java.util.concurrent…
- CallerRunsPolicy: 哪来的去哪里
- DiscardPolicy: 队列满了,丢掉任务,不会抛出异常
- DiscardOldestPolicy:队列满了,尝试和最早的竞争,,有不抛出异常
import java.util.concurrent.*;
/**
* @Description Executors 工具类,三大方法
* 四种拒绝策略
* AbortPolicy:线程池满了,等待区(阻塞队列也满了)抛出异常:Task com.fly.juc.pool.Test$$Lambda$1/558638686@568db2f2 rejected from java.util.concurrent.....
* CallerRunsPolicy: 哪来的去哪里
* DiscardPolicy: 队列满了,丢掉任务,不会抛出异常
* DiscardOldestPolicy:队列满了,尝试和最早的竞争,,有不抛出异常
* @Author cai feifei
*/
public class Test {
public static void main(String[] args) {
//自定义线程池
ThreadPoolExecutor threadPools = new ThreadPoolExecutor(2,
5,
3,
TimeUnit.SECONDS,
new LinkedBlockingQueue<>(3),
Executors.defaultThreadFactory(),
new ThreadPoolExecutor.DiscardOldestPolicy());
try {
for(int i=0;i<10;i++){
//使用线程池后,用线程池来创建线程
final int temp = i;
threadPools.execute(()->{
System.out.println(Thread.currentThread().getName() +"执行");
});
}
} catch (Exception e) {
e.printStackTrace();
} finally {
//线程池的线程使用后,一定要关闭
threadPools.shutdown();
}
}
}
最大线程该如何定义
- CUP密集型:几核CPU就是几,可以保持cpu效率最高
- IO密集型:最大线程>(大于)判断系统中十分耗IO的线程(一般为这个线程数的两倍)
//获取cpu核数
Runtime.getRuntime().availableProcessors();
上一篇:JUC详解6——读写锁
下一篇:JUC详解8