zoukankan      html  css  js  c++  java
  • 线程池

    线程池

    线程池:三大方法、7大参数、4种拒绝策略

    线程池的好处:

    1、降低资源的消耗
    2、提高响应的速度
    3、方便管理。
    线程复用、可以控制最大并发数、管理线程

    线程池:三大方法

    image-20200803223950399

    // Executors 工具类、3大方法
    public class poolTest {
        public static void main(String[] args) {
            //单个线程
    //        Executors.newSingleThreadExecutor();
            //创建固定数量线程的线程池
    //        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();
            }
        }
    }
    

    7大参数

    源码:

        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,//21亿多
                                          60L, TimeUnit.SECONDS,
                                          new SynchronousQueue<Runnable>());
        }
    //本质都是调用ThreadPoolExecutor
    //最终会调用
    //共7个参数
    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;
        }
    

    手动创建线程池

    /**
     * 4种拒绝策略
     * new ThreadPoolExecutor.AbortPolicy() // 队列满了还有线程进来,不处理这个线程,抛出异常
     * new ThreadPoolExecutor.CallerRunsPolicy() // 不处理哪里来的回哪里去
     * new ThreadPoolExecutor.DiscardPolicy() //队列满了,丢掉任务,不会抛出异常!
     * new ThreadPoolExecutor.DiscardOldestPolicy() //队列满了,尝试去和最早的竞争,也不会抛出异常!
     */
    public class Demo01 {
        public static void main(String[] args) {
            // 自定义线程池!工作 ThreadPoolExecutor
            ExecutorService threadPool = new ThreadPoolExecutor(
                    2,
                    5,
                    3,
                    TimeUnit.SECONDS,
                    new LinkedBlockingDeque<>(3),
                    Executors.defaultThreadFactory(),
                    new ThreadPoolExecutor.DiscardOldestPolicy());  //队列满了,尝试去和最早的竞争,也不会抛出异常!
            try {
                // 最大承载:Deque + max
                // 超过 RejectedExecutionException
                for (int i = 1; i <= 9; i++) {
                    // 使用了线程池之后,使用线程池来创建线程
                    threadPool.execute(()->{
                        System.out.println(Thread.currentThread().getName()+" ok");
                    });
                }
    
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                // 线程池用完,程序结束,关闭线程池
                threadPool.shutdown();
            }
    
        }
    }
    

    小结

    池的最大的大小如何去设置!
    了解:IO密集型,CPU密集型:(调优)

    public class Demo01 {
        public static void main(String[] args) {
            // 自定义线程池!工作 ThreadPoolExecutor
    
            // 最大线程到底该如何定义
            // 1、CPU 密集型,几核,就是几,可以保持CPu的效率最高!
            // 2、IO  密集型   > 判断你程序中十分耗IO的线程,
            // 程序   15个大型任务  io十分占用资源!
    
            // 获取CPU的线程数,如4核8线程返回8
            System.out.println(Runtime.getRuntime().availableProcessors());
    
            ExecutorService threadPool = new ThreadPoolExecutor(
                    2,
                    Runtime.getRuntime().availableProcessors(),
                    3,
                    TimeUnit.SECONDS,
                    new LinkedBlockingDeque<>(3),
                    Executors.defaultThreadFactory(),
                    new ThreadPoolExecutor.DiscardOldestPolicy());  //队列满了,尝试去和最早的竞争,也不会抛出异常!
            try {
                // 最大承载:Deque + max
                // 超过 RejectedExecutionException
                for (int i = 1; i <= 9; i++) {
                    // 使用了线程池之后,使用线程池来创建线程
                    threadPool.execute(()->{
                        System.out.println(Thread.currentThread().getName()+" ok");
                    });
                }
    
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                // 线程池用完,程序结束,关闭线程池
                threadPool.shutdown();
            }
    
        }
    }
    

    视频参考https://www.bilibili.com/video/BV1B7411L7tE
    上一篇:阻塞队列
    下一篇:4大函数式接口

  • 相关阅读:
    Cassandra
    POST和GET方法
    webx流程
    Cassandra的内部数据存储结构
    Session和Cookie
    昆爷又发了4篇siggraph2010,牛A...榜样和目标...
    真正开博了
    ebook搜索,I can! cool!
    (转)计算机图形学的学习
    3D图形学习的现在和将来(转)
  • 原文地址:https://www.cnblogs.com/junlinsky/p/13443302.html
Copyright © 2011-2022 走看看