了解线程池(二)七大参数和四种拒绝策略


线程池的七大参数


由于线程池的三大方法都是new ThreadPoolExecutor
所以我们看一下ThreadPoolExecutor

  public ThreadPoolExecutor(int corePoolSize, // 核心线程池大小
int maximumPoolSize, // 最大核心线程池大小
long keepAliveTime, // 超时了没有人调用就会释放
TimeUnit unit, // 超时单位
BlockingQueue<Runnable> workQueue, // 阻塞队列
ThreadFactory threadFactory, // 线程工厂:创建线程的,一般
不用动
RejectedExecutionHandler handle // 拒绝策略) {
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;
}

2.手动创建一个线程池

package com.thread.threadpool;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.*;
public class Deom01 {
    public static void main(String[] args) {
        // 自定义线程池!工作 ThreadPoolExecutor
        List  list = new ArrayList();
        ExecutorService threadPool = new ThreadPoolExecutor(
                2,           Runtime.getRuntime().availableProcessors(),
                3,
                TimeUnit.SECONDS,
                new LinkedBlockingDeque<>(3),
                Executors.defaultThreadFactory(),
                new ThreadPoolExecutor.DiscardOldestPolicy()); 
        try {
            // 超过 RejectedExecutionException
            for (int i = 1; i <= 20; i++) {
                // 使用线程池来创建线程
                threadPool.execute(()->{
                    System.out.println(Thread.currentThread().getName()+" ok");
                });
            }

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            // 线程池用完,程序结束,关闭线程池
            threadPool.shutdown();
        }

    }
}


3.四大拒绝策略

  • new ThreadPoolExecutor.AbortPolicy() //丢弃任务并抛出RejectedExecutionException异常
  • new ThreadPoolExecutor.CallerRunsPolicy() // 由调用线程(提交任务的线程)处理该任务,这里是main线程去执行
  • new ThreadPoolExecutor.DiscardPolicy() /丢掉任务,不会抛出异常!
  • new ThreadPoolExecutor.DiscardOldestPolicy() //尝试去和最早的竞争,也不会抛出异常!

4. 最大线程到底该如何定义
1、CPU 密集型,几核,就是几,可以保持CPU的效率最高!
2、IO 密集型 最大线程数> 判断你程序中十分耗IO的线程,
3、获取你电脑的CPU的核数
System.out.println(Runtime.getRuntime().availableProcessors());*

上一篇:Java线程池相关知识


下一篇:C++线程池ThreadPoolExecutor实现原理