线程池-Executors默认线程池
概述 : JDK对线程池也进行了相关的实现,在真实企业开发中我们也很少去自定义线程池,而是使用JDK中自带的线程池。
我们可以使用Executors中所提供的静态方法来创建线程池
static ExecutorService newCachedThreadPool() 创建一个默认的线程池
static newFixedThreadPool(int nThreads) 创建一个指定最多线程数量的线程池
代码实现 :
//Executors — 可以帮助我们创建线程池对象
//ExecutorService — 可以帮助我们控制线程池
public static void main(String[] args) throws InterruptedException {
//创建一个线程池对象,池子中默认是空的,里面能容纳最大的int类型
ExecutorService executorService = Executors.newCachedThreadPool();
//Executors — 可以帮助我们创建线程池对象
//ExecutorService — 可以帮助我们控制线程池
executorService.submit(()->{
System.out.println(Thread.currentThread().getName()+“线程执行了”);
});
Thread.sleep(3000);
executorService.submit(()->{
System.out.println(Thread.currentThread().getName()+"线程执行了");
});
executorService.shutdown();
}
线程池-Executors创建指定上限的线程池
使用Executors中所提供的静态方法来创建线程池
static ExecutorService newFixedThreadPool(int nThreads) : 创建一个指定最多线程数量的线程池
ExecutorService executorService = Executors.newFixedThreadPool(10);
ThreadPoolExecutor pool = (ThreadPoolExecutor)executorService;
System.out.println(pool.getPoolSize());
executorService.submit(() -> {
System.out.println(Thread.currentThread().getName() + "线程执行了");
});
executorService.submit(() -> {
System.out.println(Thread.currentThread().getName() + "线程执行了");
});
executorService.submit(() -> {
System.out.println(Thread.currentThread().getName() + "线程执行了");
});
System.out.println(pool.getPoolSize());
}
public static void main(String[] args) {
// 参数一:核心线程数量
// 参数二:最大线程数
// 参数三:空闲线程最大存活时间
// 参数四:时间单位
// 参数五:任务队列
// 参数六:创建线程工厂
// 参数七:任务的拒绝策略
ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(3, 5, 60,
TimeUnit.SECONDS, new ArrayBlockingQueue<>(10),
Executors.defaultThreadFactory(), new ThreadPoolExecutor.AbortPolicy());
}
}
public ThreadPoolExecutor(int corePoolSize,
int maximumPoolSize,
long keepAliveTime,
TimeUnit unit,
BlockingQueue workQueue,
ThreadFactory threadFactory,
RejectedExecutionHandler handler)
corePoolSize: 核心线程的最大值,不能小于0
maximumPoolSize:最大线程数,不能小于等于0,maximumPoolSize >= corePoolSize
keepAliveTime: 空闲线程最大存活时间,不能小于0
unit: 时间单位
workQueue: 任务队列,不能为null
threadFactory: 创建线程工厂,不能为null
handler: 任务的拒绝策略,不能为null
在这里插入图片描述
线程池-非默认任务拒绝策略
RejectedExecutionHandler是jdk提供的一个任务拒绝策略接口,它下面存在4个子类。
ThreadPoolExecutor.AbortPolicy: 丢弃任务并抛出RejectedExecutionException异常。是默认的策略。
ThreadPoolExecutor.DiscardPolicy: 丢弃任务,但是不抛出异常 这是不推荐的做法。
ThreadPoolExecutor.DiscardOldestPolicy: 抛弃队列中等待最久的任务 然后把当前任务加入队列中。
ThreadPoolExecutor.CallerRunsPolicy: 调用任务的run()方法绕过线程池直接执行。
public class Demo04 {
public static void main(String[] args) {
ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(3, 5, 300, TimeUnit.SECONDS, new ArrayBlockingQueue<>(4),
Executors.defaultThreadFactory(), new ThreadPoolExecutor.AbortPolicy());
for (int i = 0; i < 8; i++) {
threadPoolExecutor.submit(()->{
System.out.println(Thread.currentThread().getName()+"程序执行了");
});
}
}