【概述】:
用于存放线程的池子,有任务需要执行时,才会创建线程对象,当任务执行完毕,线程对象归还给池子。
【默认线程池创建】:
static ExecutorService newCachedThreadPool():创建一个默认的线程池
static ExecutorService newFixedThreadPool(int nThreads):创建一个指定最多线程数量的线程池
例:
ExecutorService executorService1 = Executors.newCachedThreadPool();
ExecutorService executorService2 = Executors.newFixedThreadPool(10);
【成员方法】:
List
void shutdown():启动有序关闭,其中先前提交的任务将被执行,但不会接受任何新任务
例:
ExecutorService executorService = Executors.newCachedThreadPool();
executorService.submit(() -> {
System.out.println(Thread.currentThread().getName() + "在执行了");
});
executorService.submit(() -> {
System.out.println(Thread.currentThread().getName() + "在执行了");
});
executorService.shutdown();
【线程池的构造方法】:
ThreadPoolExecutor(int corePoolSize, int maximumPoolSize, long keepAliveTime, TimeUnit unit, BlockingQueue
【参数含义】:
int corePoolSize:核心线程数量(不能小于0)
int maximumPoolSize:线程池中最大线程的数量(不能小于等于0,最大数量 >= 核心线程数量)
long keepAliveTime:空闲线程最大存活时间(值)(不能小于0)
TimeUnit unit:空闲时间(单位)(时间单位)---TimeUnit
BlockingQueue
ThreadFactory threadFactory:创建线程工厂(不能为null)---按照默认的方式创建线程对象
RejectedExecutionHandler handler:任务的拒绝策略(不能为null)
ThreadPoolExecutor pool = new ThreadPoolExecutor(
2,
5,
2,
TimeUnit.SECONDS,
new ArrayBlockingQueue<>(10),
Executors.defaultThreadFactory(),
new ThreadPoolExecutor.AbortPolicy());
pool.submit(new MyRunnable());
pool.submit(new MyRunnable());
pool.shutdown();
【注意】:
任务拒绝策略的方法:
ThreadPoolExecutor.AbortPolicy:丢弃任务并抛出RejectedExecutionException异常。是默认的策略。
ThreadPoolExecutor.DiscardPolicy:丢弃任务,但是不抛出异常 这是不推荐的做法。
ThreadPoolExecutor.DiscardOldestPolicy:抛弃队列中等待最久的任务 然后把当前任务加入队列中。
ThreadPoolExecutor.CallerRunsPolicy:调用任务的run()方法绕过线程池直接执行。



