栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

Java多线程之线程池

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

Java多线程之线程池

Java线程池
  • 线程池
    • 线程池三大方法
    • 线程池七大参数
    • 四种拒绝策略

线程池

使用线程池可以不用频繁的创建线程,而是复用已经创建的线程,这样可以降低开销、控制最大并发数

线程池三大方法
  1. Executors.newSingleThreadExecutor();只包含单线程的线程池
  2. Executors.newFixedThreadPool(5);创建一个固定大小的线程池,线程池大小通过传入的参数设置
  3. Executors.newCachedThreadPool();创建一个根据需要创建新线程的线程池,但在可用时将重新使用以前构造的线程

源码

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());
    }

三个源码的均是通过ThreadPoolExecutor 创建线程池,看下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;
   }
线程池七大参数

由上述源码得知有7个参数

int corePoolSize:核心线程数 
   如果超过corePoolSize但小于maximumPoolSize线程运行,则仅当队列已满时才会创建一个新线程
int maximumPoolSize:最大核心线程数
long keepAliveTime:如果池当前具有多于corePoolSize线程,若有线程空闲超过keepAliveTime,则多余的线程将被终止
TimeUnit unit:超时单位
BlockingQueue workQueue:阻塞队列
 1. 如果少于corePoolSize线程正在运行,Executor总是喜欢添加一个新线程,而不是排队。 
 2. 如果corePoolSize或更多的线程正在运行,Executor总是喜欢排队请求而不是添加一个新的线程。
 3. 如果请求无法排队,则会创建一个新线程,除非这将超出maximumPoolSize,否则任务将被拒绝。
ThreadFactory threadFactory:线程工厂,创建线程使用
RejectedExecutionHandler handler:拒绝策略
四种拒绝策略
提供了四个预定义的处理程序策略: 
在默认ThreadPoolExecutor.AbortPolicy ,处理程序会引发运行RejectedExecutionException后排斥反应,抛出异常。 
 public static void main(String[] args) {
        ExecutorService executorService = new ThreadPoolExecutor(
                2,
                5,
                3,
                TimeUnit.SECONDS,
                new LinkedBlockingDeque<>(3),
                Executors.defaultThreadFactory(),
                new ThreadPoolExecutor.AbortPolicy()
        );
        try {
            for (int i = 1; i <= 9; i++) {
                executorService.execute(()->{
                    System.out.println(Thread.currentThread().getName()+"----ok");
                });
            }
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            executorService.shutdown();
        }
    }

执行结果
pool-1-thread-2----ok
pool-1-thread-2----ok
pool-1-thread-2----ok
pool-1-thread-2----ok
pool-1-thread-1----ok
pool-1-thread-3----ok
pool-1-thread-5----ok
pool-1-thread-4----ok
java.util.concurrent.RejectedExecutionException: Task com.song.pool.Demo02$$Lambda$1/1831932724@7699a589 rejected from java.util.concurrent.ThreadPoolExecutor@58372a00[Running, pool size = 5, active threads = 4, queued tasks = 0, completed tasks = 4]
	at java.util.concurrent.ThreadPoolExecutor$AbortPolicy.rejectedExecution(ThreadPoolExecutor.java:2063)
	at java.util.concurrent.ThreadPoolExecutor.reject(ThreadPoolExecutor.java:830)
	at java.util.concurrent.ThreadPoolExecutor.execute(ThreadPoolExecutor.java:1379)
	at com.song.pool.Demo02.main(Demo02.java:23)
在ThreadPoolExecutor.CallerRunsPolicy中,调用execute本身的线程运行任务。 这提供了一个简单的反馈控制机制,将降低新任务提交的速度,哪来的回哪由调用者处理。 
public static void main(String[] args) {
        ExecutorService executorService = new ThreadPoolExecutor(
                2,
                5,
                3,
                TimeUnit.SECONDS,
                new LinkedBlockingDeque<>(3),
                Executors.defaultThreadFactory(),
                new ThreadPoolExecutor.CallerRunsPolicy()
        );
        try {
            for (int i = 1; i <= 9; i++) {
                executorService.execute(()->{
                    System.out.println(Thread.currentThread().getName()+"----ok");
                });
            }
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            executorService.shutdown();
        }
    }


执行结果
pool-1-thread-1----ok
main----ok
pool-1-thread-1----ok
pool-1-thread-5----ok
pool-1-thread-3----ok
pool-1-thread-2----ok
pool-1-thread-5----ok
pool-1-thread-1----ok
pool-1-thread-4----ok
在ThreadPoolExecutor.DiscardPolicy中 ,简单地删除无法执行的任务。 
public static void main(String[] args) {
        ExecutorService executorService = new ThreadPoolExecutor(
                2,
                5,
                3,
                TimeUnit.SECONDS,
                new LinkedBlockingDeque<>(3),
                Executors.defaultThreadFactory(),
                new ThreadPoolExecutor.DiscardPolicy()
        );
        try {
            for (int i = 1; i <= 9; i++) {
                executorService.execute(()->{
                    System.out.println(Thread.currentThread().getName()+"----ok");
                });
            }
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            executorService.shutdown();
        }
    }

执行结果

pool-1-thread-1----ok
pool-1-thread-4----ok
pool-1-thread-1----ok
pool-1-thread-3----ok
pool-1-thread-2----ok
pool-1-thread-1----ok
pool-1-thread-4----ok
pool-1-thread-5----ok
在ThreadPoolExecutor.DiscardOldestPolicy中 ,如果执行程序没有关闭,则工作队列头部的任务被删除,然后重试执行(可能会再次失败,导致重复)
public static void main(String[] args) {
        ExecutorService executorService = new ThreadPoolExecutor(
                2,
                5,
                3,
                TimeUnit.SECONDS,
                new LinkedBlockingDeque<>(3),
                Executors.defaultThreadFactory(),
                new ThreadPoolExecutor.DiscardOldestPolicy()
        );
        try {
            for (int i = 1; i <= 9; i++) {
                executorService.execute(()->{
                    System.out.println(Thread.currentThread().getName()+"----ok");
                });
            }
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            executorService.shutdown();
        }
    }
执行结果
pool-1-thread-1----ok
pool-1-thread-2----ok
pool-1-thread-3----ok
pool-1-thread-3----ok
pool-1-thread-4----ok
pool-1-thread-5----ok
pool-1-thread-3----ok
pool-1-thread-1----ok
pool-1-thread-4----ok
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/930743.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号