线程池ThreadPoolExecutor (三大方法、7大参数、四种拒绝策略)





池化技术

线程的运行,本质:占用系统的资源!优化资源的使用!=> 池化技术
线程池 连接池 内存池 对象池
池化技术:事先准备好一些资源,使用拿走,不使用还给我。

线程池的好处:

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

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

线程池三大方法

在这里插入图片描述

public class PoolTest1 {

	public static void main(String[] args) {
		//ExecutorService pool = Executors.newSingleThreadExecutor();//单个线程池
		//ExecutorService pool = Executors.newFixedThreadPool(5);//固定线程池
		ExecutorService pool = Executors.newCachedThreadPool();//缓存 可伸缩
		
		try {
			for (int i = 0; i < 10; i++) {
				pool.execute(()->{
					System.out.println(Thread.currentThread().getName());
				});
			}
		} catch (Exception e) {
			e.getStackTrace();
		} finally {
			//需要关闭
			pool.shutdown();
		}
	}
}

Executors.newSingleThreadExecutor()单个线程池

在这里插入图片描述

Executors.newFixedThreadPool(5)固定线程池

在这里插入图片描述

Executors.newCachedThreadPool()缓存 可伸缩

在这里插入图片描述

7大参数

    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对象

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

int corePoolSize, //核心线程大小

int maximumPoolSize, //最大线程大小

long keepAliveTime, //超时释放时间

TimeUnit unit, //超时单位

BlockingQueue workQueue, //阻塞队列

ThreadFactory threadFactory, //线程工程(一般不动)

RejectedExecutionHandler handler //拒绝策略

四种拒绝策略

	public static void main(String[] args) {
		ThreadPoolExecutor poolExecutor = new ThreadPoolExecutor(
				2, 
				5, 
				2, 
				TimeUnit.SECONDS,
				new LinkedBlockingDeque<>(3),
				Executors.defaultThreadFactory(),
				new ThreadPoolExecutor.AbortPolicy()
				);
		
		try {
			//最大承载 Deque + max
			for (int i = 1; i <= 10; i++) {
				poolExecutor.execute(()->{
					System.out.println(Thread.currentThread().getName());
				});
			}
		} catch (Exception e) {
			e.getStackTrace();
		} finally {
			poolExecutor.shutdown();
		}
	}

在这里插入图片描述

当线程池的任务缓存队列已满并且线程池中的线程数目达到maximumPoolSize时,如果还有任务到来就会采取任务拒绝策略

ThreadPoolExecutor.AbortPolicy 丢弃任务并抛出RejectedExecutionException异常。

ThreadPoolExecutor.DiscardPolicy 丢弃任务,但是不抛出异常。

ThreadPoolExecutor.DiscardOldestPolicy 丢弃队列最前面的任务,然后重新提交被拒绝的任务

ThreadPoolExecutor.CallerRunsPolicy 由调用线程(提交任务的线程)处理该任务

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

一只小小狗

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

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

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

打赏作者

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

抵扣说明:

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

余额充值