JDK提供2种线程池,ThreadPoolExecutor、ForkJoinPool
这里先写ThreadPoolExecutor 有时间再写ForkJoinPool
ThreadPoolExecutor
JDK提供4种默认的线程池,实际上他们的底层都是ThreadPoolExecutor,通过传入构造方法的7个参数实现不同的功能
Executors.newSingleThreadExecutor(); // 单个线程的线程池
Executors.newCachedThreadPool(); // 0个核心线程
Executors.newFixedThreadPool(4); // 固定4个线程
Executors.newScheduledThreadPool(2); //
分别查看源码,分析7个参数,即可知其作用
前3个都比较简单,主要写下第四个
ScheduledThreadPool
public class ScheduledPoolTest {
public static void main(String[] args) {
ScheduledExecutorService scheduledExecutorService = Executors.newScheduledThreadPool(4);
// 固定时间定时的去执行任务 参数分别是
// 1.任务
// 2.要延迟多久执行第一个任务
// 3.任务执行推迟时间
// 4.时间单位
scheduledExecutorService.scheduleAtFixedRate(()->{
System.out.println(Thread.currentThread().getName());
},0,500, TimeUnit.MILLISECONDS);
}
}
7个参数
public ThreadPoolExecutor(int corePoolSize,
int maximumPoolSize,
long keepAliveTime,
TimeUnit unit,
BlockingQueue<Runnable> workQueue,
ThreadFactory threadFactory,
RejectedExecutionHandler handler) {
查看4个默认线程池的源码,很容易知道他们的作用
从execute方法源码分析线程池执行任务过程
public void execute(Runnable command) {
if (command == null)
throw new NullPointerException();
/*
* Proceed in 3 steps:
*
* 1. If fewer than corePoolSize threads are running, try to
* start a new thread with the given command as its first
* task. The call to addWorker atomically checks runState and
* workerCount, and so prevents false alarms that would add
* threads when it shouldn't, by returning false.
*
* 2. If a task can be successfully queued, then we still need
* to double-check whether we should have added a thread
* (because existing ones died since last checking) or that
* the pool shut down since entry into this method. So we
* recheck state and if necessary roll back the enqueuing if
* stopped, or start a new thread if there are none.
*
* 3. If we cannot