- package com.kuang.pool;
-
- import java.util.concurrent.ExecutorService;
- import java.util.concurrent.Executors;
- //Executors工具类 三大方法
- //使用线程池,创建线程
- public class Demo01 {
- public static void main(String[] args) {
- // ExecutorService threadPool = Executors.newSingleThreadExecutor();//单个线程。
- //ExecutorService threadPool = Executors.newFixedThreadPool(5);// 创建一个固定的线程池的大小。阻塞队列无线大,创建线程固定
- ExecutorService threadPool = Executors.newCachedThreadPool();//创建一个可伸缩的,遇强则强,遇弱则弱。 创建线程无线大,阻塞队列就一个容量
-
- try {
- for (int i = 0; i < 100; i++) {
- threadPool.execute(()->{
- System.out.println(Thread.currentThread().getName()+" ok");
- });
- }
- } catch (Exception e) {
- e.printStackTrace();
- } finally {
- threadPool.shutdown();
- }
-
-
-
- }
- }
- public static ExecutorService newSingleThreadExecutor() {
- return new FinalizableDelegatedExecutorService
- (new ThreadPoolExecutor(1, 1,
- 0L, TimeUnit.MILLISECONDS,
- new LinkedBlockingQueue
())); - }
- public static ExecutorService newFixedThreadPool(int nThreads) {
- return new ThreadPoolExecutor(nThreads, nThreads,
- 0L, TimeUnit.MILLISECONDS,
- new LinkedBlockingQueue
()); - }
- public static ExecutorService newCachedThreadPool() {
- return new ThreadPoolExecutor(0, Integer.MAX_VALUE,
- 60L, TimeUnit.SECONDS,
- new SynchronousQueue
()); - }
本质是:new ThreadPoolExecutor
源码分析
- public ThreadPoolExecutor(int corePoolSize,
- int maximumPoolSize,
- long keepAliveTime,
- TimeUnit unit,
- BlockingQueue
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;
- }
- public ThreadPoolExecutor(int corePoolSize,//核心线程池大小
- int maximumPoolSize,//最大核心线池大小
- long keepAliveTime,//超时了没有人调用就会释放
- TimeUnit unit,//超时单位
- BlockingQueue
workQueue,//阻塞队列 - ThreadFactory threadFactory,//线程工厂,创建线程的,一般不用动
- RejectedExecutionHandler handler) {// 拒绝策略
new
- package com.kuang.pool;
-
- import java.security.AccessController;
- import java.util.concurrent.*;
-
- import static java.util.concurrent.Executors.newSingleThreadExecutor;
-
- //Executors工具类 三大方法
- //使用线程池,创建线程
-
- /**
- * 第一种拒绝策略 new ThreadPoolExecutor.AbortPolicy() 超出,则不去执行那个多的,而且会抛异常RejectedExecutionException
- * 第二种拒绝策略 new ThreadPoolExecutor.CallerRunsPolicy() 哪个线程的创建出的这个线程,就回到哪个线程去执行
- * 第三种拒绝策略 new ThreadPoolExecutor.DiscardPolicy() 队列满了 丢掉任务, 不去执行,也不抛异常
- * 第四种拒绝策略 new ThreadPoolExecutor.DiscardOldestPolicy() 队列满了,会抛弃任务队列中最旧的任务也就是最先加入队列的,再把这个新任务添加进去。也不会抛异常!!!
- *
- */
- public class Demo01 {
- public static void main(String[] args) {
- // ExecutorService threadPool = Executors.newSingleThreadExecutor();//单个线程。
- //ExecutorService threadPool = Executors.newFixedThreadPool(5);// 创建一个固定的线程池的大小。阻塞队列无线大,创建线程固定
- // ExecutorService threadPool = Executors.newCachedThreadPool();//创建一个可伸缩的,遇强则强,遇弱则弱。 创建线程无线大,阻塞队列就一个容量
- ExecutorService threadPool = new ThreadPoolExecutor(2
- , 5,
- 3,
- TimeUnit.SECONDS,
- new LinkedBlockingQueue<>(3),
- Executors.defaultThreadFactory(),
- new ThreadPoolExecutor.DiscardOldestPolicy()//银行满了,还有人进来,不处理这个人的,抛出异常.
- );
-
- try {
- //最大承载: Deque+max =5+3=8
- //超过 RejectedExecutionException
- for (int i =1; i <=9; i++) {
- int finalI = i;
- threadPool.execute(()->{
- System.out.println(Thread.currentThread().getName()+" ok"+ finalI);
- });
- }
- } catch (Exception e) {
- e.printStackTrace();
- } finally {
- threadPool.shutdown();
- }
-
-
-
- }
-
-
-
-
-
- }
1、CPU密集型 CPU的内核为几, 最大线程就定义为几,可以保持CPU的效率最高!
代码获取CPU的核数
System.out.println("CPU核心为:"+Runtime.getRuntime().availableProcessors());
2、IO密集型 判断 你程序中十分耗IO的线程 就把最大线程定义 >15 比如
程序 15 个大型任务,io十分占用资源,就设置最大线程定义为30