【JUC并发编程系列】线程池简介

一、线程池概述

线程池其实就是一种多线程处理形式,处理过程中可以将任务添加到队列中,然后在创建线程后自动启动这些任务。这里的线程可以通过实现Runnable或Callable接口的实例对象;

线程池的优势:

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

特点:

  • 降低资源消耗:通过重复利用已创建的线程降低线程创建和销毁造成的消耗。
  • 提高响应速度:当任务到达时、任务可以不需要等待线程的创建就能立即执行。
  • 提高线程的可管理性:线程是稀缺资源、如果无限制的创建、不仅会消耗系统资源、还会降低系统的稳定性、使用线程池可以进行统一的分配、调优和监控。
  • Java中实现线程池是通过Executor框架实现的、框架中用到了Executor、Executors、ExecutorService、ThreadPoolExecutor这几个类。

架构

在这里插入图片描述

二、线程池的使用方式

一池N线程

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

    }

一池一线程

// 一池一线程
        ExecutorService threadPool01 = Executors.newSingleThreadExecutor();

        try {
            // 多个请求
            for (int i = 0; i < 10; i++) {
                threadPool01.execute(() -> {
                    System.out.println(Thread.currentThread().getName() + " 办理业务 ");
                });
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            // 关闭
            threadPool01.isShutdown();
        }

可扩容线程

// 可扩容线程
        ExecutorService threadPool02 = Executors.newCachedThreadPool();`

        try {
            // 多个请求
            for (int i = 0; i < 10; i++) {
                threadPool02.execute(() -> {
                    System.out.println(Thread.currentThread().getName() + " 办理业务 ");
                });
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            // 关闭
            threadPool02.isShutdown();
        }

源码解析

public static ExecutorService newFixedThreadPool(int nThreads) {
        return new ThreadPoolExecutor(nThreads, nThreads,
                                      0L, TimeUnit.MILLISECONDS,
                                      new LinkedBlockingQueue<Runnable>());
    }
public static ExecutorService newSingleThreadExecutor() {
        return new FinalizableDelegatedExecutorService
            (new ThreadPoolExecutor(1, 1,
                                    0L, TimeUnit.MILLISECONDS,
                                    new LinkedBlockingQueue<Runnable>()));
    }
public static ExecutorService newCachedThreadPool() {
        return new ThreadPoolExecutor(0, Integer.MAX_VALUE,
                                      60L, TimeUnit.SECONDS,
                                      new SynchronousQueue<Runnable>());
    }

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

三、线程池参数简介

  • int corePoolSize 常驻线程数量
  • int maximumPoolSize 线程池里最大线程的数量
  • long keepAliveTime 线程存活时间
  • TimeUnit unit 时间单位
  • BlockingQueue workQueue 阻塞队列
  • ThreadFactory threadFactory 线程工厂
  • RejectedExecutionHandler handler 拒绝策率

工作流程

在这里插入图片描述

1、当线程进来时、首先会进入到 corepool 里面。
2、当 corepool 满了会进入到阻塞队列里面。
3、阻塞队列满了会进入到 maximumpool。
4、当 maximumpool 也满了、会执行拒绝策率。

简述拒绝策率

  • 默认策率 abortPolicy:直接抛出RejectdExecutionException异常、阻止系统正常运行。
  • CallerRunPolicy: 该策率既不会抛弃任务、也不会抛弃异常、而是将任务退回到调用者、从而降低新任务的流量
  • DiscardOldesPolicy: 抛弃队列中等待最久的任务、然后把当前任务加入队列中、尝试再次提交当前任务
  • DiscardPolicy: 该策率默默的丢弃无法处理的异常、不予任何处理也不抛弃异常。

四、自定义线程池

为何不允许使用系统线程池

【强制】线程池不允许使用Executor去创建、而是通过ThreadPoolExecutor的方式、明确线程池运行规则、规避资源耗尽的风险
说明:Executor返回的线程池对象弊端如下:
1)FixedThreadPool 和 SingleThreadPool:
允许请求的队列长度为 Integer.MAX_VALUE、可能会堆积大量的请求、从而导致OOM
2)CacheThreadPool 和 ScheduledThreadPool :
允许请求的队列长度为 Integer.MAX_VALUE、可能会堆积大量的请求、从而导致OOM

public static void main(String[] args) {
        ExecutorService threadPool = new ThreadPoolExecutor(2,
                5,
                2L,
                TimeUnit.SECONDS,
                new ArrayBlockingQueue<>(3),
                Executors.defaultThreadFactory(),
                new ThreadPoolExecutor.AbortPolicy());
        try {
            // 多个请求
            for (int i = 0; i < 10; i++) {
                threadPool.execute(() -> {
                    System.out.println(Thread.currentThread().getName() + " 办理业务 ");
                });
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            // 关闭
            threadPool.isShutdown();
        }
        
    }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值