前言
工作中很多地方都用到了线程池,不仅可以减少线程不停创建,销毁对资源的消耗,还能极大地提高资源利用率 ,
今天就线程池做一个详尽介绍
干货
/**
* seven big param
* 核心线程数
* 最大线程数
* 存活时间(非核心线程空闲)
* 存活时间单位
* 存放线程的队列(等待执行任务的一个阻塞对列)
* 创建线程的工厂类
* 当请求达到一定值时的一个执行策略
* AbortPolicy (默认策略,抛弃新增任务,并给调用线程抛出异常)
* DiscardPolicy(抛弃新增任务,不抛异常)
* DiscardOldestPolicy(喜新厌旧【把新任务添加到线程池执行,抛弃线程池里面待的最久的任务】)
* CallerRunsPolicy(自己处理不了,直接返还调用者)
*/
public static void main(String[] args) throws InterruptedException {
int corePoolThread = Runtime.getRuntime().availableProcessors();
System.out.println("corePoolThread = " + corePoolThread);
final ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(corePoolThread, corePoolThread * 2, 3, TimeUnit.SECONDS, new LinkedBlockingDeque<>(200), Executors.defaultThreadFactory(), new ThreadPoolExecutor.CallerRunsPolicy());
// final ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(corePoolThread, corePoolThread * 2, 3, TimeUnit.SECONDS, new LinkedBlockingDeque<>(200), new CustomizableThreadFactory("functionName-Thread-Pool-"), new ThreadPoolExecutor.CallerRunsPolicy());
// final ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(corePoolThread, corePoolThread * 2, 3, TimeUnit.SECONDS, new LinkedBlockingDeque<>(200), myThread->{
Thread thread = new Thread(myThread);
thread.setName("业务pool-");
thread.setUncaughtExceptionHandler((t,e)->{
System.out.println(t.getName() + t.getId()+ " 在 " + new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()) +" 发生异常,堆栈信息:" + e);
});
return thread;
}, new ThreadPoolExecutor.CallerRunsPolicy());
CountDownLatch countDownLatch = new CountDownLatch(210);
for (int i = 0; i < 210; i++) {
int finalI = i;
threadPoolExecutor.execute(() -> {
System.out.println("测试数据-execute = " + finalI + "---"+Thread.currentThread().getName());
countDownLatch.countDown();
try {
Thread.sleep(10);
} catch (InterruptedException e) {
e.printStackTrace();
threadPoolExecutor.shutdown();
}
});
if(i==209){
System.out.println("运行中====================>"+threadPoolExecutor.getActiveCount());
}
}
countDownLatch.await();
System.out.println(threadPoolExecutor.getActiveCount());
TimeUnit.SECONDS.sleep(4);
System.out.println(threadPoolExecutor.getActiveCount());
}
验证一下执行顺序
-
i < corePoolThread +200 ,没有创建新线程
2.
-
i< num num>corePoolThread +200 有线程创建
-

i< num num>maxpool(corePoolThread * 2) 执行策略开始执行

2905



被折叠的 条评论
为什么被折叠?



