线程池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 由调用线程(提交任务的线程)处理该任务

猜你喜欢

转载自blog.csdn.net/jj89929665/article/details/112983350