线程池

2.线程池(3+7+4)
为什么会有池?-----提高程序的性能,提高使用率,降低消耗。
3种方法
(注意,阿里开发手册不允许使用这三种方法,容易OOM)
Executors 可以有三种创立线程池的方法。
 public static void main(String[] args) {
        // Executors 通过这个工具类产生
        // 单例的 只有一个线程
        ExecutorService executor = Executors.newSingleThreadExecutor();
        // 固定的线程数
        ExecutorService executor2 = Executors.newFixedThreadPool(8);
        // 弹性池 可伸缩(最大不超过2147483647个)
        ExecutorService executor3 = Executors.newCachedThreadPool();
        // 使用线程池
        executor.execute(()->{
            System.out.println("里面是个Runnable接口 可以用表达式");
        });
        // 线程池关闭
        executor.shutdown();
    }

7大参数
为什么阿里不允许使用呢?----点进去的源码都是用ThreadPoolExecutor,会使用阻塞队列,最大值是integer.MAX_VALUE 会造成OOM。
 new ThreadPoolExecutor(0, Integer.MAX_VALUE,
                                      60L, TimeUnit.SECONDS,
                                      new SynchronousQueue<Runnable>());
new ThreadPoolExecutor(nThreads, nThreads,
                                      0L, TimeUnit.MILLISECONDS,
                                      new LinkedBlockingQueue<Runnable>());
ThreadPoolExecutor(1, 1, 0L, TimeUnit.MILLISECONDS,
                                    new LinkedBlockingQueue<Runnable>())
    // 对应的构造器
  public ThreadPoolExecutor(int corePoolSize, // 常用池子的大小
                              int maximumPoolSize, //  最大线程池大小
                              long keepAliveTime,// 差量线程等待时间数值
                              TimeUnit unit,// 时间单位
                              BlockingQueue<Runnable> workQueue)//阻塞队列类型

点进去看线程池的源码发现生成线程池的7个参数,
public ThreadPoolExecutor(int corePoolSize, // 核心池线程数大小 (常用)
                              int maximumPoolSize,  // 最大的线程数大小 (常用)
                              long keepAliveTime, // 超时等待时间 (常用)
                              TimeUnit unit, // 时间单位 (常用)
                              BlockingQueue<Runnable> workQueue, // 阻塞队列(常用)
                              ThreadFactory threadFactory, // 线程工厂
                              RejectedExecutionHandler handler // 拒绝策略(常用))

4种拒绝策略
报错,丢弃异常ThreadPoolExecutor.AbortPolicy();
不报错,丢弃任务ThreadPoolExecutor.DiscardPolicy();
失效前尝试获取资源hreadPoolExecutor.DiscardOldestPolicy();
哪儿来的回哪儿去ThreadPoolExecutor.CallerRunsPolicy();
下面的是相关的源码Runnable 是调用的线程r,ThreadPoolExecutor 线程池e
 public static class CallerRunsPolicy implements RejectedExecutionHandler {
        public CallerRunsPolicy() { }
     // r为进入的线程 关闭时 执行r的行为-----即哪儿来的回哪儿去
        public void rejectedExecution(Runnable r, ThreadPoolExecutor e) {
            if (!e.isShutdown()) {
                r.run();
            }
        }
    }
  public static class AbortPolicy implements RejectedExecutionHandler {
        public AbortPolicy() { }
      // 生成拒绝执行异常RejectedExecutionException
        public void rejectedExecution(Runnable r, ThreadPoolExecutor e) {
            throw new RejectedExecutionException("Task " + r.toString() +
                                                 " rejected from " +
                                                 e.toString());
        }
    }
    public static class DiscardPolicy implements RejectedExecutionHandler { 
        public DiscardPolicy() { }
        // 与上面的差一个报错 即不进行报错
        public void rejectedExecution(Runnable r, ThreadPoolExecutor e) {
        }
    }
    public static class DiscardOldestPolicy implements RejectedExecutionHandler {
        public DiscardOldestPolicy() { }
        // e在关闭之前是试着执行
        public void rejectedExecution(Runnable r, ThreadPoolExecutor e) {
            if (!e.isShutdown()) {
                e.getQueue().poll();
                e.execute(r);
            }
        }
    }

最大线程池 该如何设置--------
CPU密集型: 根据CPU的处理器数量来定!保证最大效率
IO密集型: 50 个线程都是进程操作大io资源, 比较耗时! > 这个常用的 IO 任务数!
查看计算机cpu数的方法(java.lang)
Runtime.getRuntime().availableProcessors();
1
————————————————
版权声明:本文为CSDN博主「Amusing ourselves to death」的原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接及本声明。
原文链接:https://blog.csdn.net/weixin_45568648/article/details/104702882
posted @ 2020-03-06 21:58  jack-jin  阅读(91)  评论(0)    收藏  举报