目录
一.线程池的创建(四种)
1.newFixedThreadPool(定长线程池,超出会到队列中等待,不建议使用)
2.newCachedThreadPool(可缓存线程池,需要时创建,不需要时回收)
3.newSingleThreadExecutor(单线程化的线程池,按优先级执行)
4.newScheduledThreadPool (定长线程池,支持定时及周期性任务执行)
为什么不建议使用 newFixedThreadPool ?
我们先引出线程池需要部分的变量:
1.corePoolSize(核心线程数)
2.maximumPoolSize(线程池所能容纳最大线程数)
3.keepAliveTime(非核心线可程闲置时间)
4.workQueue(队列)
5.threadFacory(线程工厂)
6.handler(拒绝策略)
不建议直接使用Executors.newFixedThreadPool是因为这个接口会赋予线程池所需要变量一个默认值,且这个值相对较大容易会浪费很多资源,还有一个原因是默认给予队列长度MAX_VALUE会导致OOM(Out Of Memory内存不够)。
自定义线程池:new ThreadPoolExecutor
public static ExecutorService getInstance(int corePoolSize,
int maximumPoolSize,
long keepAliveTime) {
if (instance == null) {
synchronized (SeatrendThreadPool.class) {
if (instance == null) {
ThreadPoolExecutor threadPoolExecutor =
new ThreadPoolExecutor(corePoolSize, maximumPoolSize, keepAliveTime, TimeUnit.MILLISECONDS,
new LinkedBlockingQueue<Runnable>(1000), new ThreadPoolExecutor.DiscardOldestPolicy());
instance = threadPoolExecutor;
}
}
}
return instance;
}
队列可设置为1000,一个比较稳定的数值,也可以根据需要去调整。
这里主要是想讲一下拒绝策略(RejectedExecutionHandler)(四种)
拒绝策略也可以说是针对队列满了时任务无法添加进来如何去处理
1.ThreadPoolExecutor.AbortPolicy(丢弃任务,抛出RejectedExecutionException异常)
2.ThreadPoolExecutor.DiscardPolicy(丢弃任务,不抛出异常)
3.ThreadPoolExecutor.DiscardOldestPolicy(丢弃队列最前面的任务,然后重新提交被拒绝的任务)
4.ThreadPoolExecutor.CallerRunsPolicy(由提交任务的线程来执行该任务)
二.线程的使用
1.闭锁
public Result method(areas) {
//自定义线程池(没有自定义线程池类就直接new ThreadPoolExecutor(...))
ExecutorService instance = 自定义的线程池类.getInstance(20, 500, 0);
//定义计数器初始值
final CountDownLatch countDownLatch = new CountDownLatch(areas.size());
areas.forEach(area -> {
instance.execute(() -> {
try {
xxx..
} catch (Exception e) {
System.out.println(e.getLocalizedMessage());
} finally {
//计数-1
countDownLatch.countDown();
}
});
});
try {
//等待计数器归零
countDownLatch.await();
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
// 关闭线程池
instance.shutdown();
instance.shutdownNow();
}
return new Result..setMsg(ResultCode.SUCESS, xxx);
}