ThreadPoolExecutor类的七大构造参数
corePoolSize 在创建了线程池后,默认情况下,线程池中并没有任何线程,而是等待有任务到来才创建线程去执行任务。默认情况下,在创建了线程池后,线程池中的线程数为0,当有任务来之后,就会创建一个线程去执行任务,当线程池中的线程数目达到corePoolSize后,就会把到达的任务放到缓存队列当中。
maxPoolSize 当线程数大于或等于核心线程,且任务队列已满时,线程池会创建新的线程,直到线程数量达到maxPoolSize。如果线程数已等于maxPoolSize,且任务队列已满,则已超出线程池的处理能力,线程池会拒绝处理任务而抛出异常。
keepAliveTime 当线程空闲时间达到keepAliveTime,该线程会退出,直到线程数量等于corePoolSize。如果allowCoreThreadTimeout设置为true,则所有线程均会退出直到线程数量为0。正常情况下,核心线程是一直存活着的。
unit 空闲时间单位
workQueue 一个阻塞队列,用来存储等待执行的任务,比如说LinkedBlockingQueue、SynchronousQueue等
threadFactory 创建线程的工厂,通过自定义的线程工厂可以给每个新建的线程设置相关特性,例如设置成Daemon线程。
handler 线程池的饱和策略,当阻塞队列满了,且线程数达到了maxPoolSize,如果继续提交任务,必须采取一种策略处理该任务,默认采用拒绝策略AbortPolicy。
shutdown
public class Test {
public static void main(String
[] args
) throws InterruptedException
{
ThreadPoolExecutor executorService
= new ThreadPoolExecutor(1, 3, 30, TimeUnit
.SECONDS
,
new ArrayBlockingQueue<>(2), r
-> {
Thread t
= new Thread(r
);
return t
;
}, new ThreadPoolExecutor.AbortPolicy());
for (int i
=0;i
<5;i
++){
executorService
.execute(new Runnable() {
@Override
public void run() {
try {
TimeUnit
.SECONDS
.sleep(5);
System
.out
.println(Thread
.currentThread().getName() + " finish.");
} catch (InterruptedException e
) {
System
.out
.println(Thread
.currentThread().getName() + " InterruptedException.");
}
}
});
}
executorService
.shutdown();
executorService
.awaitTermination(1, TimeUnit
.HOURS
);
System
.out
.println("--------all finish-------");
}
}
shutdown()是非阻塞方法,所以需要调用awaitTermination等待所有任务执行完,shutdown()会将之前提交的任务都执行完,线程池才关闭。
shutdownNow
public class Test {
public static void main(String
[] args
) throws InterruptedException
{
ThreadPoolExecutor executorService
= new ThreadPoolExecutor(1, 3, 30, TimeUnit
.SECONDS
,
new ArrayBlockingQueue<>(2), r
-> {
Thread t
= new Thread(r
);
return t
;
}, new ThreadPoolExecutor.AbortPolicy());
for (int i
=0;i
<5;i
++){
executorService
.execute(new Runnable() {
@Override
public void run() {
try {
TimeUnit
.SECONDS
.sleep(5);
System
.out
.println(Thread
.currentThread().getName() + " finish.");
} catch (InterruptedException e
) {
System
.out
.println(Thread
.currentThread().getName() + " InterruptedException.");
}
}
});
}
List
<Runnable> runnables
= executorService
.shutdownNow();
for (Runnable runnable
: runnables
) {
System
.out
.println(runnable
);
}
}
}