JUC-05-池化技术与线程池

本文介绍了线程池的基本概念和技术细节,包括线程池的三大构造方法、七大参数及四种拒绝策略。通过实例演示了如何创建不同类型的线程池,并讨论了线程池在优化资源消耗、提高响应速度等方面的优势。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

线程池

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

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

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

线程池的好处

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

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

线程三大方法

package com.bjw.pool;

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

// Executors
public class Demo01 {
    public static void main(String[] args) {
        //ExecutorService threadPool = Executors.newSingleThreadExecutor(); //单个线程
        //ExecutorService threadPool2 = Executors.newFixedThreadPool(5); //创建一个固定的线程池的大小
        ExecutorService threadPool3 = Executors.newCachedThreadPool(); //可伸缩的,遇强则强,遇弱则弱


        try {
            for (int i = 0; i < 100; i++) {
                //使用了线程池之后,使用线程池来创建线程
                threadPool3.execute(()->{
                    System.out.println(Thread.currentThread().getName()+"ok");
                });
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            // 线程池用完,程序结束,关闭线程池
            threadPool3.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>());
    }
 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;
    }

在这里插入图片描述

四种拒绝策略

package com.bjw.pool;

import java.util.concurrent.*;

// Executors
/*
* ThreadPoolExecutor.AbortPolicy():RejectedExecutionException 银行满了,还有人进来,不处理这个人,抛出异常
* ThreadPoolExecutor.CallerRunsPolicy();//哪来的去哪里
* ThreadPoolExecutor.DiscardPolicy();//队列满了,丢掉任务,不抛出异常
* ThreadPoolExecutor.DiscardOldestPolicy();//队列满了,尝试和最早的竞争,也不会抛出异常
* */
public class Demo01 {
    public static void main(String[] args) {
        /*ExecutorService threadPool = Executors.newSingleThreadExecutor(); //单个线程
        ExecutorService threadPool2 = Executors.newFixedThreadPool(5); //创建一个固定的线程池的大小
        ExecutorService threadPool3 = Executors.newCachedThreadPool(); //可伸缩的,遇强则强,遇弱则弱*/
        ExecutorService threadPool = new ThreadPoolExecutor(
                2,
                5,
                3,
                TimeUnit.SECONDS,
                new LinkedBlockingDeque<>(3),
                Executors.defaultThreadFactory(),
                new ThreadPoolExecutor.DiscardPolicy()
        );

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

小结

了解:IO密集型,CPU密集型(调优)

 /*
        * 最大线程应该如何定义
        * 1、CPU密集型,几核就是几,可以保证cpu的效率最高
        * 2、IO密集型,判断程序中十分耗IO的线程
        * */
        //获取cup的核数
        System.out.println(Runtime.getRuntime().availableProcessors());
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

协奏曲❤

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值