JUC学习笔记四:线程池

线程池:3大方法,7大参数,4种拒绝策略

1.池化技术

程序运行的本质就是占用系统的资源!
使用池化技术能够更好的优化资源的使用。
包括:线程池,连接池,对象池,内存池。。。
什么是池化技术:就是事先准备好的资源,如果有人要用就来这里拿,用完再还回来。

线程池的好处:

  1. 降低资源的消耗
  2. 提高响应的速度
  3. 方便管理

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

2.三大方法

/**
 * 创建线程池的三大方法
 */
public class Demo01 {
    public static void main(String[] args) {
        //创建单个线程
        ExecutorService executorService = Executors.newSingleThreadExecutor();
        //创建固定个数线程
        ExecutorService executorService = Executors.newFixedThreadPool(5);
        //创建可变大小的线程池
        ExecutorService executorService = Executors.newCachedThreadPool();


        try {
            for (int i = 1; i < 5; i++) {
                executorService.execute(() -> {
                    System.out.println(Thread.currentThread().getName());
                });
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            //线程池使用了之后要关掉
            executorService.shutdown();
        }
    }
}

我们来查看一下源码

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

可以看到这三个方法的本质都是返回一个ThreadPoolExecutor,只不过是里面的参数不同而已。

在阿里巴巴的开发手册有这样一段描述:
在这里插入图片描述
所以我们可以通过自定义线程池,来满足我们的需要,接下来就来看如何自定义线程池。

3.七大参数

查看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.corePoolSize = corePoolSize;
        this.maximumPoolSize = maximumPoolSize;
        this.workQueue = workQueue;
        this.keepAliveTime = unit.toNanos(keepAliveTime);
        this.threadFactory = threadFactory;
        this.handler = handler;
    }

可以用一个例子来帮助理解
在这里插入图片描述
假设平常不忙的时候
银行正常开两个窗口(corePoolSize),银行总共有5个窗口(maximumPoolSize),候客区有3个位置(BlockingQueue)
那么当来的人数小于5(corePoolSize+BlockingQueue)的时候,银行是可以正常运转的,不需要把其他的窗口打开。

当人数大于5的时候,那么银行就需要把其他窗口打开,但是总数不会超过5(maximumPoolSize)

如果超过5(maximumPoolSize),这时候就需要一种拒绝策略了(下面要讲的四大策略)

    public static void main(String[] args) {
        ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(2,
                5,
                3,
                TimeUnit.SECONDS,
                new LinkedBlockingDeque<>(3),
                new ThreadPoolExecutor.AbortPolicy()
        );

        try {
            for (int i = 1; i <=9; i++) {
                threadPoolExecutor.execute(()->{
                    System.out.println(Thread.currentThread().getName());
                });
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            threadPoolExecutor.shutdown();
        }
    }

4.四大策略

在这里插入图片描述
还是用银行的例子

  1. AbortPolicy:中止,如果此时银行人数超过了最大人数,那么就不处理,抛出异常
  2. CallerRunsPolicy:哪里来的就返回给哪个调用(像刚刚的例子就返回给main线程调用)
  3. DiscardPolicy:队列满了就丢掉任务,不会抛出异常
  4. DiscardOldestPolicy:队列满了就尝试去和最早的竞争(去看正在办理的窗口有没有人办好了—类似于插队),也不会抛出异常

5.线程池的大小如何去设置

有两种类型:CPU密集型,IO密集型

  1. CPU密集型:当前计算机是几核就是几可以保持CPU的效率最高(查看当前cpu核心数:(Runtime.getRuntime().availableProcessors())
  2. IO密集型:判断你程序种十分消耗IO的线程,设置一般在他的两倍就可以了
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值