理解java并发中的线程池

1.线程池的出现

任何程序的运行和都与要耗费资源,因为程序是在操作系统上运行的,涉及到与操作系统的交互,比如我们常用的数据库连接池,没有使用池化技术之前,每一个链接的创建和关闭都需要耗费资源,现在运用池化技术,将链接的创建关闭交给池统一处理,就可以达到节约资源,减少系统消耗的目的,类似数据库连接池,线程也有自己的线程池
一个线程池中包含许多准备运行的空闲线程,将Runnable对象交给线程池,当使用线程池时,就会调用其中的线程,执行run方法,当run方法执行完毕,线程不会死亡,而是在池中为下一个请求提供服务
线程池除了能够统一的管理诸多线程,减少资源消耗之外,还有一个原因是减少并发线程数目,创建大量线程会大大降低性能,甚至导致虚拟机崩溃,总结下来,使用线程池的好处有

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

2.Executor-构建线程池

java.lang.concurrent包下有一个Executor接口,也叫执行器,·它来管理我们的线程,这里被管理的线程要实现callablerunnable接口,我们主要关注ExecutorService这个Executor的子接口,我们之后创建的线程池都是这个接口的实现类,在这里我们梳理一下这些类和接口的关系:
在这里插入图片描述
其中ThreadPoolExecutor是线程池的核心实现类,我们后面会重点介绍,Executor的作用不止用来创建线程池,还有其他作用,整个Executor系列可以说是一个线程框架体系,这里我们介绍它的创建线程池的作用

2.1Executors-并发工具类

Collection和数组都有的CollectionsArrays工具类相似,Executor也有它的工具类:Executors
在这里插入图片描述
前面我们说到了线程池,又介绍了Executor框架,现在我们通过这个工具类来创建线程池,这个类有许多静态工厂方法来创建线程池,在java中有三种线程池:

  • public static ExecutorService newSingleThreadExecutor()创建只有一个线程的线程池
  • public static ExecutorService newFixedThreadPool(int nThreads)创建固定数量线程的线程池
  • public static ExecutorService newCachedThreadPool()创建一个会根据需要而创建新线程的线程池

这三种线程池都是ExecutorService的实现类:

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

为了说明这三个线程的区别,我们分别建立三个Demo来演示这三种方法:

2.2newSingleThreadExecutor

创建只有一个线程的线程池

public class Demo {
    public static void main(String[] args) {
        ExecutorService threadPool = Executors.newSingleThreadExecutor();
        try {
            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执行任务

Process finished with exit code 0

可以发现只有一个线程来顺序的执行我们的十个任务

2.3newFixedThreadPool

public class Demo {
    public static void main(String[] args) {
        ExecutorService threadPool = Executors.newFixedThreadPool(5);
        try {
            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-2执行任务
pool-1-thread-3执行任务
pool-1-thread-4执行任务
pool-1-thread-5执行任务

我们发现是5个固定的线程来执行了10个任务,每个线程都被使用

2.4newCachedThreadPool

public class Demo {
    public static void main(String[] args) {
        ExecutorService threadPool = Executors.newCachedThreadPool();
        try {
            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-6执行任务
pool-1-thread-7执行任务
pool-1-thread-8执行任务
pool-1-thread-10执行任务
pool-1-thread-9执行任务
pool-1-thread-4执行任务
pool-1-thread-5执行任务

可以看出,该类型线程池会根据任务需要而创建线程

3.使用ThreadPoolExecutor创建线程池

3.1为什么不适用Executors

我们演示了使用工具类创建的三种线程池,我们进入newFixedThreadPool源码:
在这里插入图片描述
可以发现通过工具类创建的线程池底层是用的ThreadPoolExecutor,在《阿里巴巴java开发手册》种规定了用ThreadPoolExecutor而不是Executors创建线程池:
在这里插入图片描述

3.2源码分析ThreadPoolExecutor

既然创建线程池都是通过ThreadPoolExecutor,我们来探究一下这个实现类:

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

这是一个构造器,我们将重点放在这7个参数上,这7个参数贯穿了我们线程池的所有功能特点:

  • int corePoolSize 核心线程池大小
  • int maximumPoolSize 最大核心线程池大小
  • long keepAliveTime 超时了没有人调用就会释放
  • TimeUnit unit 超时单位
  • BlockingQueue< Runnable> workQueue 阻塞队列
  • ThreadFactory threadFactory 线程工厂:创建线程的
  • RejectedExecutionHandler handle 拒绝策略

我们举个例子来说明这些参数的作用:
在这里插入图片描述
这是一个银行,1,2号窗口代表核心线程池,表示在做任务时必须活跃的两个线程,就好比银行中始终有两个窗口是服务的,假如现在连两个窗口正在服务,那么又有其他顾客进来了,3,4,5窗口这时候是关闭的,顾客会进入候客区也就是阻塞队列等待1,2号窗口也就是核心线程完成任务后处理他们的业务,要是候客区满了,又有顾客进来,那么这时候3,4,5号窗口就要工作了,也就是我们设置的最大核心线程数量全部工作,3,4,5号线程处理完业务后,等待一段时间发现没有任务处理就会进去线程池等待下一次的任务被执行,这就是超超时等待,要是这时候队列满了,所有线程都处于工作状态,又有其他任务等待被处理该怎么办,这时候参数中的拒绝策略会起到作用,根据拒绝策略来处理这些多的线程

3.3手动设置并创建线程池

有了上面的介绍,我们来自定义一个线程池

public class Demo {
    public static void main(String[] args) {
        ExecutorService threadPool = new ThreadPoolExecutor(2,5,3,
                TimeUnit.SECONDS,
                new LinkedBlockingDeque<>(3),
                Executors.defaultThreadFactory(),
                new ThreadPoolExecutor.DiscardOldestPolicy());
        try {
            for (int i = 0; i < 10; i++) { // 使用了线程池之后,使用线程池来创建线程
                threadPool.execute(()->{
                    System.out.println(Thread.currentThread().getName() + "执行任务");
                });
            }
    }catch (Exception e) {
        e.printStackTrace();
    } finally {
        // 线程池用完,程序结束,关闭线程池
        threadPool.shutdown();
        }
    }
}

我们设置了两个核心线程数量和5个最大线程数量,以及容量为3的阻塞队列,3s的等待时长,我们设置了10个任务,按照我们的解释,这时候所有线程都会执行任务

pool-1-thread-1执行任务
pool-1-thread-2执行任务
pool-1-thread-2执行任务
pool-1-thread-2执行任务
pool-1-thread-1执行任务
pool-1-thread-3执行任务
pool-1-thread-4执行任务
pool-1-thread-5执行任务

结果确实如此,我们改变任务数量为5,也就是最大数量线程池

pool-1-thread-1执行任务
pool-1-thread-2执行任务
pool-1-thread-2执行任务
pool-1-thread-2执行任务
pool-1-thread-2执行任务

我们发现只有核心线程池在处理任务,这和我们想的一样,这里就做这两种演示,其他功能可以自己试

3.4四种拒绝策略

在上面的演示中,我们用的是new ThreadPoolExecutor.DiscardOldestPolicy()来处理多余的无法处理的线程,下面我们来介绍java线程池中的4种拒绝策略:

在这里插入图片描述

  • new ThreadPoolExecutor.AbortPolicy()任务数>最大线程数量会抛出异常: java.util.concurrent.RejectedExecutionException:
  • new ThreadPoolExecutor.CallerRunsPolicy()被原来的线程处理
  • new ThreadPoolExecutor.CallerRunsPolicy()任务数>最大线程数量不会抛出异常
  • new ThreadPoolExecutor.DiscardOldestPolicy() 队列满了,尝试去和最早的竞争,也不会 抛出异常!

4.CPU密集型和IO密集型

池的最大的大小如何去设置?最大线程到底该如何定义?要回答这两个问题先要对IO密集型,CPU密集型进行了解

  • CPU密集型:对应电脑或服务器CPU的处理器数量,几核就设置最大线程数量为几,可以使效率达到最高
  • IO密集型:判断你程序中十分耗IO的线程,比如一个程序有20个大型任务,我们就可以设置20个线程去执行这个程序
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值