10、JUC、线程池(重点)


线程池:三大类型、七大参数、四种拒绝策略

10.1、池化技术

程序的运行,本质:占用系统的资源! 优化资源的使用! =》池化技术

线程池、连接池、内存池、对象池… 创建、销毁,十分浪费资源

池化技术:事先准备好一些资源,有人要用,就来我这里拿,用完之后还给我

线程池的好处:

1、降低资源消耗

2、提高响应速度

3、方便管理

线程复用、可以控制最大并发数、管理线程

10.2、三大方法

在这里插入图片描述
方法一:newSingleThreadExecutor()

方法二:newFixedThreadPool()

方法三:newCachedThreadPool()

package com.chen.pool;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

// Executors 工具类,3大方法
// 使用了线程池
public class Demo01 {

    public static void main(String[] args) {
        // 创建一个单个线程的线程池
        ExecutorService threadPool = Executors.newSingleThreadExecutor();

        // 创建一个大小固定的线程池
        // ExecutorService threadPool = Executors.newFixedThreadPool(5);

        // 可伸缩的,遇强则强,遇弱则弱
        // ExecutorService threadPool = Executors.newCachedThreadPool();


        try {
            for (int i = 0; i < 10; i++) {
                threadPool.execute(() -> {
                    System.out.println(Thread.currentThread().getName() + "ok");
                });
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            // 线程池用完,程序结束,关闭线程池
            threadPool.shutdown();
        }

    }
}

10.3、七大参数

源码分析

newSingleThreadExecutor()

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

newFixedThreadPool(5)

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

newCachedThreadPool()

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

在这里插入图片描述

10.4、手动创建线程池

package com.chen.pool;

import java.util.concurrent.*;

// Executors 工具类,3大方法

/**
 * 四种拒绝策略
 * 1、new ThreadPoolExecutor.AbortPolicy() // 银行满了,并且还有人进来,抛出异常
 * 2、new ThreadPoolExecutor.CallerRunsPolicy() // 哪来的去哪里
 * 3、new ThreadPoolExecutor.DiscardPolicy() // 队列满了,丢掉任务,不会抛出异常
 * 4、new ThreadPoolExecutor.DiscardOldestPolicy() // 队列满了,尝试去和最早的竞争,如果竞争失败,依旧丢掉,不会报异常
 */

public class Demo01 {

    public static void main(String[] args) {

        // 自定义线程池
        ThreadPoolExecutor threadPool = new ThreadPoolExecutor(
                2, // 核心线程池大小
                5, // 最大线程池大小
                3, // 超时了没有人调用就会释放
                TimeUnit.SECONDS, // 超时单位
                new LinkedBlockingDeque<>(3), // 阻塞队列
                Executors.defaultThreadFactory(), // 线程工程,创建线程的
                new new ThreadPoolExecutor.AbortPolicy() // 队列满了,尝试去和最早的竞争,如果竞争失败,依旧丢掉,不会报异常
        );


        try {
            // 最大承载:Deque + max
            // 超过 RejectedExecutionException
            for (int i = 1; i <= 9; i++) {
                threadPool.execute(() -> {
                    System.out.println(Thread.currentThread().getName() + "ok");
                });
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            // 线程池用完,程序结束,关闭线程池
            threadPool.shutdown();
        }

    }
}

10.5、四种拒绝策略

在这里插入图片描述
1、new ThreadPoolExecutor.AbortPolicy() // 银行满了,并且还有人进来,抛出异常

在这里插入图片描述
2、new ThreadPoolExecutor.CallerRunsPolicy() // 哪来的去哪里

在这里插入图片描述
3、new ThreadPoolExecutor.DiscardPolicy() // 队列满了,丢掉任务,不会抛出异常

在这里插入图片描述
4、new ThreadPoolExecutor.DiscardOldestPolicy() // 队列满了,尝试去和最早的竞争,如果竞争失败,依旧丢掉,不会报异常

10.6、小结核拓展

池的最大的大小如何去设置!

了解:IO密集型,CPU密集型

package com.chen.pool;

import java.util.concurrent.*;

public class Demo01 {

    public static void main(String[] args) {

        // 自定义线程池

        // 最大线程池应该如何定义
        // 1、CPU 密集型 几核,就是几,可以保持CPU的效率最高
        // 2、IO 密集型 > 判断你程序中十分耗IO的线程
        //        程序  15个大型任务  io十分占用资源

        // 获取CPU的核数
        System.out.println(Runtime.getRuntime().availableProcessors());

        ThreadPoolExecutor threadPool = new ThreadPoolExecutor(
                2,
                5,
                3,
                TimeUnit.SECONDS,
                new LinkedBlockingDeque<>(3),
                Executors.defaultThreadFactory(),
                new ThreadPoolExecutor.DiscardOldestPolicy() // 队列满了,尝试去和最早的竞争,如果竞争失败,依旧丢掉,不会报异常
        );


        try {
            // 最大承载:Deque + max
            // 超过 RejectedExecutionException
            for (int i = 1; i <= 9; i++) {
                threadPool.execute(() -> {
                    System.out.println(Thread.currentThread().getName() + "ok");
                });
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            // 线程池用完,程序结束,关闭线程池
            threadPool.shutdown();
        }

    }
}

学校视频链接:https://www.bilibili.com/video/BV1B7411L7tE?p=24

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值