常用的五种类型线程池
- newFixedThreadPool
- newCachedThreadPool
- newSingleThreadExecutor
- newScheduledThreadPool
- newWorkStealingPool
newFixedThreadPool
定长线程池,控制线程最大并发数,超出的任务会在队列中等待。
public static void main(String[] args) {
ExecutorService pool = Executors.newFixedThreadPool(3);
for (int i = 0; i < 6; i++) {
pool.execute(()->{
System.out.println("当前线程:"+Thread.currentThread().getName());
});
}
}
当前线程:pool-1-thread-1
当前线程:pool-1-thread-2
当前线程:pool-1-thread-1
当前线程:pool-1-thread-3
当前线程:pool-1-thread-1
当前线程:pool-1-thread-2
始终只有线程1 2 3在工作
newCachedThreadPool
可缓存的线程池,当有任务进来会先检查是否有线程处于空闲状态,有的话则会分配任务,没有的话会创建一个新的线程。当线程空闲一定时间后会被回收。
public static void main(String[] args) throws InterruptedException {
ExecutorService pool = Executors.newCachedThreadPool();
for (int i = 0; i < 6; i++) {
pool.execute(()->{
System.out.println("当前线程:"+Thread.currentThread().getName());
});
TimeUnit.MICROSECONDS.sleep(500);
}
}
控制台输出
当前线程:pool-1-thread-1
当前线程:pool-1-thread-2
当前线程:pool-1-thread-2
当前线程:pool-1-thread-2
当前线程:pool-1-thread-2
当前线程:pool-1-thread-2
如果线程处理不过来任务会新建线程,线程之间存在复用
newSingleThreadExecutor
线程池中只有一个线程按照顺序工作
public static void main(String[] args) {
ExecutorService pool = Executors.newSingleThreadExecutor();
for (int i = 0; i < 6; i++) {
pool.execute(()->{
System.out.println("当前线程:"+Thread.currentThread().getName());
});
}
}
控制台输出
当前线程:pool-1-thread-1
当前线程:pool-1-thread-1
当前线程:pool-1-thread-1
当前线程:pool-1-thread-1
当前线程:pool-1-thread-1
当前线程:pool-1-thread-1
newScheduledThreadPool
public static void main(String[] args) {
ScheduledExecutorService pool = Executors.newScheduledThreadPool(2);
Runnable task = new Runnable() {
@Override
public void run() {
System.out.println(new Date() +":当前线程:"+Thread.currentThread().getName());
}
};
//2秒后第一次执行,之后每隔3秒执行一次
pool.scheduleAtFixedRate(task, 2, 3, TimeUnit.SECONDS);
}
控制台输出(2秒后第一次执行,之后每隔3秒执行一次)
Mon Dec 07 15:42:33 CST 2020:当前线程:pool-1-thread-1
Mon Dec 07 15:42:36 CST 2020:当前线程:pool-1-thread-1
Mon Dec 07 15:42:39 CST 2020:当前线程:pool-1-thread-1
newWorkStealingPool
newWorkStealingPool,这个是 JDK1.8 版本加入的一种线程池,stealing 翻译为抢断、窃取的意思。假设共有三个线程同时执行, A, B, C,当A,B线程池尚未处理完任务时,而C已经处理完毕,则C线程会从A或者B中窃取任务执行, 假如A线程中的队列里面分配了5个任务,而B线程的队列中分配了1个任务,当B线程执行完任务后,它会主动的去A线程中窃取其他的任务进行执行,WorkStealingPool 背后是使用 ForkJoinPool实现的
public class Main {
public static void main(String[] args) throws IOException {
// CPU 核数
int nCpu = Runtime.getRuntime().availableProcessors();
System.out.println(nCpu);
// workStealingPool 会自动启动cpu核数个线程去执行任务
ExecutorService service = Executors.newWorkStealingPool();
// 我的cpu核数为8 放入9个任务,其中第一个是1s执行完毕,其余都是2s执行完毕,
service.execute(new R(1000));
// 有一个任务会进行等待,当第一个执行完毕后,会再次偷取第九个任务执行
for (int i = 0; i < nCpu; i++) {
service.execute(new R(2000));
}
// 因为work stealing 是deamon线程,守护线程需要对对主线程阻塞
System.in.read();
}
static class R implements Runnable {
int time;
R(int time) {
this.time = time;
}
@Override
public void run() {
try {
TimeUnit.MILLISECONDS.sleep(time);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName() + " " + time);
}
}
}
控制台输出
8
ForkJoinPool-1-worker-1 1000
ForkJoinPool-1-worker-2 2000
ForkJoinPool-1-worker-4 2000
ForkJoinPool-1-worker-3 2000
ForkJoinPool-1-worker-5 2000
ForkJoinPool-1-worker-0 2000
ForkJoinPool-1-worker-7 2000
ForkJoinPool-1-worker-6 2000
ForkJoinPool-1-worker-1 2000
不使用框架线程池的创建
使用给定的初始参数创建一个新的ThreadPoolExecutor。
-
corePoolSize
核心线程数,即使在空闲时也要保留在池中的线程数 -
maximumPoolSize
当核心线程都在忙碌,任务量数较大时,新建临时线程+核心线最大线程数 -
keepAliveTime
多余的空闲线程最大空闲时间,到达时间后线程将被销毁 -
unit
时间单位 -
workQueue
当线程都在忙碌时将任务保留于队列中。该队列只能存放了实现了Runnable接口的对象 -
threadFactory
创建新线程时要使用的工厂 -
handler
当workQueue满时的拒绝策略,JDK本身提供了四种拒绝策略,自己也可以通过实现RejectedExecutionHandler自定义拒绝策略
7.1 abortPolicy 抛弃任务,抛出RejectedExecutionException异常
7.2 DiscardPolicy(默认) 抛弃任务,也不抛出异常
7.3 DiscardOldestPolicy 丢弃队列中队首任务,重新尝试执行任务
7.4 CallerRunsPolicy 调用者回退机制 让Runnable自身执行
ExecutorService pool = new ThreadPoolExecutor(int corePoolSize,
int maximumPoolSize,
long keepAliveTime,
TimeUnit unit,
BlockingQueue<Runnable> workQueue,
ThreadFactory threadFactory,
RejectedExecutionHandler handler)