线程池
线程池的方法:
- static ExecutorService newCachedThreadpool ():创建一个默认的线程池
- static newFixedthreadpool (int nThreads):创建一个指定最多线程数量的线程池
示例:
public class MyThreadPoolDemo1 {
public static void main(String[] args) throws InterruptedException {
ExecutorService executorService = Executors.newCachedThreadPool();
// executorService.submit( 多线程执行的任务 );
executorService.submit(()->{
System.out.println(Thread.currentThread().getName() + " is running...");
});
// Thread.sleep(1000);//在等待过程中复用线程1
executorService.submit(()->{
System.out.println(Thread.currentThread().getName() + " is running...");
});
executorService.shutdown();
}
}
- //static Executorservice newFixedthreadpool (int nThreads)
- //创建一个指定最多线程数量的线程池
示例:
public class MyThreadPoolDemo2 {
public static void main(String[] args) {
//参数不是初始值而是最大值,一开始创建完成后,里面的线程仍是0
ExecutorService executorService = Executors.newFixedThreadPool(10);
ThreadPoolExecutor tpe = (ThreadPoolExecutor) executorService;
//获取线程池数量
System.out.println(tpe.getPoolSize());
//线程一
executorService.submit(()->
System.out.println("running..."));
//线程二
executorService.submit(()->
System.out.println("running too..."));
//获取线程池数量
System.out.println(tpe.getPoolSize());
executorService.shutdown();
}
}
线程池的详细用例:
(详见代码及注释)
public static void main(String[] args) {
//ThreadPoolExecutor tpe =
//new ThreadPoolExecutor(
//1、核心线程数量,
//2、最大线程数,
//3、空闲线程最大存活时间,
//4、空闲线程时间单位,
//5、任务队列,
//6、创建线程工厂,
//7、任务的拒绝策略 )
ThreadPoolExecutor tpe = new ThreadPoolExecutor(
5, // 核心线程数量
10, // 最大线程数
2, // 空闲线程最大存活时间
TimeUnit.SECONDS, // 空闲线程时间单位
new ArrayBlockingQueue<>(5), // 任务队列
Executors.defaultThreadFactory(), // 创建线程工厂
new ThreadPoolExecutor.AbortPolicy()); // 任务的拒绝策略
tpe.submit(()->
System.out.println("running...."));
tpe.shutdown();
}
线程池的几种拒绝策略:
- ThreadPoolExecutor.AbortPolicy:丢弃任务并抛出RejectedExecutionException异常。是默认的策略。
- ThreadPoolExecutor.DiscardPolicy :丢弃任务,但是不抛出异常这是不推荐的做法
- ThreadPoolExecutor.DiscardOldestPolicy: 抛弃队列中等待最久的任务然后把当前任务加入队列中。
- ThreadPoolExecutor.CallerRunsPolicy:调用任务的run0方法绕过线程池直接执行
何时触发线程池的拒绝策略:
- 任务数 - 阻塞队列长度 > 最大线程数 触发拒绝策略。
- 任务数 > 最大线程数 + 阻塞队列长度 触发拒绝策略。
示例:
public static void main(String[] args) {
ThreadPoolExecutor tpe = new ThreadPoolExecutor(
2,//核心线程数量
5,//最大线程数
2,//空闲线程最大存活时间
TimeUnit.SECONDS,//空闲线程时间单位
new ArrayBlockingQueue<>(10),//任务队列
Executors.defaultThreadFactory(),//创建线程工厂
new ThreadPoolExecutor.AbortPolicy());//任务的拒绝策略
for (int i=1;i<=16;i++) {//当
tpe.submit(()->
System.out.println("running...."));
}
tpe.shutdown();
}
运行结果: