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

    1、线程池的介绍

    1)

    线程池做的工作只要是控制运行的线程数量,处理过程中将任务放入队列,然后在线程创建后启动这些任务,
    如果线程数量超过了最大数量,超出数量的线程排队等候,等其他线程执行完毕,再从队列中取出任务来执行。

    2)

    它的主要特点为:线程复用;控制最大并发数;管理线程。

    2、线程池的优势

    第一:降低资源消耗。通过重复利用已创建的线程降低线程创建和销毁造成的销耗。
    第二:提高响应速度。当任务到达时,任务可以不需要等待线程创建就能立即执行。
    第三:提高线程的可管理性。线程是稀缺资源,如果无限制的创建,不仅会销耗系统资源,还会降低系统的稳定性,使用线程池可以进行统一的分配,调优和监控

    3、线程池的三大方法

    Java中的线程池是通过Executor框架实现的,该框架中用到了Executor,Executors,ExecutorService,ThreadPoolExecutor这几个类

    ExecutorService接口用的比较多 实现类为ThreadPoolExecutor
    Executors相当于Arrays

    3.1、Executors.newFixedThreadPool(int n)

    /**
    public class MyThreadPoolDemo {
    	public static void main(String[] args) {
    		ExecutorService threadPool = Executors.newFixedThreadPool(5); // 一池5个受理线程
    
    		try {
    			// 模拟10个顾客办理业务 但是只有5个员工办理业务
    			for (int i = 0; i < 10; i++) {
    				threadPool.execute(() -> {
    					System.out.println(Thread.currentThread().getName() + "	 办理业务");
    				});
    			}
    		} catch (Exception e){
    			e.printStackTrace();
    		}finally {
    			threadPool.shutdown();
    		}
    		// pool-1-thread-1	 办理业务
    		// pool-1-thread-3	 办理业务
    		// pool-1-thread-2	 办理业务
    		// pool-1-thread-3	 办理业务
    		// pool-1-thread-2	 办理业务
    		// pool-1-thread-3	 办理业务
    		// pool-1-thread-3	 办理业务
    		// pool-1-thread-2	 办理业务
    		// pool-1-thread-4	 办理业务
    		// pool-1-thread-5	 办理业务
    	}
    }
    
    

    源码

    public static ExecutorService newFixedThreadPool(int nThreads) {
        return new ThreadPoolExecutor(nThreads, nThreads,
                                      0L, TimeUnit.MILLISECONDS,
                                      new LinkedBlockingQueue<Runnable>());
    }
    
    

    newFixedThreadPool创建的线程池corePoolSize和maximumPoolSize值是相等的,它使用的是LinkedBlockingQueue
    执行长期任务性能好, 创建一个线程池 , 一个线程池里有N个固定线程, 即有固定线程数的线程池

    3.2、newSingleThreadExecutor

    public class MyThreadPoolDemo {
    	public static void main(String[] args) {
    		ExecutorService threadPool = Executors.newSingleThreadExecutor(); // 一池一个受理线程
    
    		try {
    			// 模拟10个顾客办理业务 但是只有5个员工办理业务
    			for (int i = 0; i < 10; i++) {
    				threadPool.execute(() -> {
    					System.out.println(Thread.currentThread().getName() + "	 办理业务");
    				});
    			}
    		} catch (Exception e){
    			e.printStackTrace();
    		}finally {
    			threadPool.shutdown();
    		}
    		// pool-1-thread-1	 办理业务
    		// pool-1-thread-1	 办理业务
    		// pool-1-thread-1	 办理业务
    		// pool-1-thread-1	 办理业务
    		// pool-1-thread-1	 办理业务
    		// pool-1-thread-1	 办理业务
    		// pool-1-thread-1	 办理业务
    		// pool-1-thread-1	 办理业务
    		// pool-1-thread-1	 办理业务
    		// pool-1-thread-1	 办理业务
    	}
    }
    
    

    源码

    public static ExecutorService newSingleThreadExecutor() {
        return new FinalizableDelegatedExecutorService
            (new ThreadPoolExecutor(1, 1,
                                    0L, TimeUnit.MILLISECONDS,
                                    new LinkedBlockingQueue<Runnable>()));
    }
    

    newSingleThreadExecutor 创建的线程池corePoolSize和maximumPoolSize值都是1,它使用的是LinkedBlockingQueue
    一个任务一个任务的执行 , 一个线程池一个线程

    3.3、newCachedThreadPool

    public class MyThreadPoolDemo {
    	public static void main(String[] args) {
    		ExecutorService threadPool = Executors.newCachedThreadPool(); // 一池N个受理线程
    
    		try {
    			// 模拟10个顾客办理业务 但是只有5个员工办理业务
    			for (int i = 0; i < 10; i++) {
    				threadPool.execute(() -> {
    					System.out.println(Thread.currentThread().getName() + "	 办理业务");
    				});
    			}
    		} catch (Exception e){
    			e.printStackTrace();
    		}finally {
    			threadPool.shutdown();
    		}
    		// pool-1-thread-1	 办理业务
    		// pool-1-thread-2	 办理业务
    		// pool-1-thread-3	 办理业务
    		// pool-1-thread-4	 办理业务
    		// pool-1-thread-5	 办理业务
    		// pool-1-thread-6	 办理业务
    		// pool-1-thread-9	 办理业务
    		// pool-1-thread-8	 办理业务
    		// pool-1-thread-10	 办理业务
    		// pool-1-thread-7	 办理业务
    	}
    }
    
    

    源码

    public static ExecutorService newCachedThreadPool() {
        return new ThreadPoolExecutor(0, Integer.MAX_VALUE,
                                      60L, TimeUnit.SECONDS,
                                      new SynchronousQueue<Runnable>());
    }
    

    newCachedThreadPool创建的线程池将corePoolSize设置为0,将maximumPoolSize设置为Integer.MAX_VALUE,它使用的是SynchronousQueue,
    也就是说来了任务就创建线程运行,当线程空闲超过60秒,就销毁线程。

    执行很多短期异步认为 线程池根据需要创建新线程, 但在先前构建的线程可用时将重用他们, 可扩容

    4、线程池的七大参数

    /**
         * Creates a new {@code ThreadPoolExecutor} with the given initial
         * parameters.
         *
         * @param corePoolSize 线程池的常驻核心线程数
         * @param maximumPoolSize 线程池中能狗容纳同时执行的最大线程数,此值必须大于等于1
         * @param keepAliveTime 多于线程的存或时间 当线程池中的线程数量超过corePoolSize时,
         *                      当空闲时间到达keepAlivetime时, 多余线程会被销毁知道只剩下corePoolSize个线程位为止
         * @param unit    keepAliveTime 的单位
         * @param workQueue  任务队列, 被提交但尚未被执行的任务
         * @param threadFactory  表示生产线程池中工作线程的线程工厂 (一般默认即可)
         * @param handler   拒绝策略, 表示队列满了,并且工作线程大于等于线程池的最大数maximumPoolSize时, 
         * 					如何来拒绝请求执行的Runable的策略
        */
        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.corePoolSize = corePoolSize;
            this.maximumPoolSize = maximumPoolSize;
            this.workQueue = workQueue;
            this.keepAliveTime = unit.toNanos(keepAliveTime);
            this.threadFactory = threadFactory;
            this.handler = handler;
        }
    
    

    5、线程池的底层工作原理



    线程池用哪个

    自定义线程池



    线程池的拒绝策略

    JDK内置决绝策略

    ThreadPoolExecutor.AbortPolicy() 默认情况

    直接抛出RejectedExecutionException 异常阻止系统正常运行

    ThreadPoolExecutor. CallerRunsPolicy()

    “调用者运行” 一种调节机制, 该策略既不会抛弃任务, 也不会抛出异常, 而是将某些任务回退到调用者, 从而降低新任务的流量.

    ThreadPoolExecutor.DiscardPolicy()

    该策略默默的丢弃无法处理的任务, 不予任何处理也不抛出异常, 如果允许任务丢失,这是最好的一种策略

    ThreadPoolExecutor.DiscardOldestPolicy()

    抛弃队列中等待最久的任务, 然后把当前任务加到队列中,尝试再次提交当前任务

    以上拒绝策略都实现了
    RejectExcutionHandle接口

    参数设置

    CPU密集型
    最大线程数 是运行环境的cpu内核数 + 1

    System.out.println(Runtime.getRuntime().availableProcessors());
    

    IO密集型
    一种考虑到IO密集型,大部分线程都阻塞,因此需要多配置线程数 :
    参考公式 : cpu核数 /(1 - 阻塞系数) 阻塞系数:0.8 ~ 0.9
    比如8核cpu :8 / (1 - 0.9)=80个线程数

  • 相关阅读:
    iOS MVC <模型-视图-控制器>
    iOS interface building 大纲视图内容
    循序渐进VUE+Element 前端应用开发(28)--- 附件内容的管理 (转载)
    循序渐进VUE+Element 前端应用开发(27)--- 数据表的动态表单设计和数据存储(转载)
    ABP框架中一对多,多对多关系的处理以及功能界面的处理(2)(转载)
    ABP框架中一对多,多对多关系的处理以及功能界面的处理(1)(转载)
    电商商品数据库的设计和功能界面的处理 (转载)
    循序渐进VUE+Element 前端应用开发(26)--- 各种界面组件的使用(2)(转载)
    循序渐进VUE+Element 前端应用开发(25)--- 各种界面组件的使用(1)(转载)
    循序渐进VUE+Element 前端应用开发(24)--- 修改密码的前端界面和ABP后端设置处理(转载)
  • 原文地址:https://www.cnblogs.com/xidianzxm/p/14296402.html
Copyright © 2011-2022 走看看