目录
2.1 Excutors.newFixedThreadPool(int)
2.2 Excutors.newSingleThreadExecutor(int)
2.3 Excutors.newCachedThreadPool(int)
2.4 Excutors.newScheduledThreadPool(int)
2.5 Excutors.newSingleThreadScheduledExecutor(int)
2.6 Excutors.newWorkStealingPool(int)
6.1 自定义线程池(即自己传入参数来new ThreadPoolExcutor)使用案例
1.概述
ThreadPoolExecutor 是线程池的核心实现
2.Excutors创建线程池的6种方式
2.1 Excutors.newFixedThreadPool(int)
- 创建固定线程数的线程池
(1)使用案例
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class MyThreadPoolDemo {
public static void main(String[] args) {
ExecutorService threadPool = Executors.newFixedThreadPool(5);//一个池5个线程
//模拟10个用户来办理业务,每个用户就是来自于外部的请求线程
try {
for (int i = 0; i < 10; i++) {
threadPool.execute(()->{
System.out.println(Thread.currentThread().getName()+"\t办理业务");
});
}
}catch (Exception e){
e.printStackTrace();
}finally {
threadPool.shutdown();
}
}
}
- 可以发现只有5个线程被复用去处理业务
(2)源码及特点
主要特点:
- 1.创建一个定长线程池,可控制线程最大并发数,超出的线程会在队列种等待
- 2.创建的线程池corePoolSize和maximumPoolSize值是相等的,它使用的是LinkedBlockingQueue
2.2 Excutors.newSingleThreadExecutor(int)
- 创建只有一个线程的线程池
(1)使用案例
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class MyThreadPoolDemo {
public static void main(String[] args) {
ExecutorService threadPool = Executors.newSingleThreadExecutor();//一个池1个线程
//模拟10个用户来办理业务,每个用户就是来自于外部的请求线程
try {
for (int i = 0; i < 10; i++) {
threadPool.execute(()->{
System.out.println(Thread.currentThread().getName()+"\t办理业务");
});
}
}catch (Exception e){
e.printStackTrace();
}finally {
threadPool.shutdown();
}
}
}
- 可以发现只有一个线程处理任务
(2)源码及特点
主要特点:
- 1.创建一个单线程化的线程池,它只会用唯一的工作线程来执行任务,保证所有任务按照指定顺序执行
- 2.创建的线程池corePoolSize和maximumPoolSize值都设置为1,它使用的是LinkedBlockingQueue
注意:
newFixedThreadPool(1,threadFactory)
不等价于newSingleThreadExecutor
newSingleThreadExecutor
创建的线程池保证内部只有一个线程执行任务,并且线程数不可扩展;- 而通过
newFi