线程池说明
创建线程池,然后把任务丢给线程池。正常的过程是这样的,当你把任务提交给线程池的时候,它会看下当前正在跑的线程有多少个,如果说<你配置的核心线程数,它直接new一个线程去执行你的任务,如果达到了核心线程数,它会把任务放到一个队列里排队,等待空闲线程执行,如果队列满了,它会执行拒绝策略。
线程池核心元素
核心线程数量,最大线程数,空闲线程最大存活时间,时间单位,任务队列,创建线程工厂,任务的拒绝策略
任务拒绝策略
- ThreadPoolExecutor.AbortPolicy:丢弃任务并抛出RejectedExecutionException异常。默认策略。
- ThreadPoolExecutor.DiscardPolicy:丢弃任务,但是不抛出异常,这是不推荐的做法。
- ThreadPoolExecutor.DiscardOldestPolicy:抛弃队列中等待最久的任务,然后把当前任务加入队列中。
- ThreadPoolExecutor.CallerRunsPolicy:调用任务的run()方法绕过线程池直接执行。(不用线程池,自己创建新线程执行任务)
代码示例
@Data
@Configuration
@ConfigurationProperties(prefix = "offline")
public class ThreadPoolConfig {
/**
* 核心线程数
*/
private int core;
/**
* 最大线程数
*/
private int max;
/**
* 队列长度
*/
private int queue;
/**
* 当线程数大于核心数时,剩余空闲线程在终止前等待新任务的最大时间。
*/
private int keepalive;
}
private final ThreadPoolExecutor threadPoolExecutor;
...
this.threadPoolExecutor = new ThreadPoolExecutor(threadPoolConfig.getCore(),
threadPoolConfig.getMax(),
threadPoolConfig.getKeepalive(),
TimeUnit.SECONDS,
new ArrayBlockingQueue<>(threadPoolConfig.getQueue()),
new NamedThreadFactory("xxx", true),
new ThreadPoolExecutor.CallerRunsPolicy());
this.threadPoolExecutor.allowCoreThreadTimeOut(true);
...
//有任务需要执行时,创建线程对象执行任务(池中线程数小于核心线程数时)。任务执行完毕,线程对象放入池子中。
threadPoolExecutor.execute(...);
//所有的任务执行完毕,关闭线程池。
threadPoolExecutor.shutdown();
注:线程池中 submit()和 execute()方法都是执行方法,区别在于execute()只能执行 Runnable 类型的任务,submit()可以执行 Runnable 和 Callable 类型的任务,Callable 类型的任务可以获取执行的返回值,而 Runnable 执行无返回值。