1. 什么是线程池?
线程池其实就是将多个线程对象放到一个容器当中。
2. 为什么使用线程池?
可以重用线程,减少创建和销毁线程带来的消耗。
3.线程池的工作原理?
4. 如何使用线程池?
要想知道如何使用线程池,就要先知道线程池的种类有多少种?线程池大概有以下几种:
- ThreadPoolExecutor
- FixedThreadPool
- CahcedThreadPool
- SingleThreadExecutor
- ScheduledThreadPool
以下介绍这几种线程池的用法:
3.1 ThreadPoolExecutor
ThreadPoolExecutor 是线程池真正的实现方法,以下是 ThreadPoolExecutor 的构造方法:
public ThreadPoolExecutor(int corePoolSize,
int maximumPoolSize,
long keepAliveTime,
TimeUnit unit,
BlockingQueue<Runnable> workQueue) {
this(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue,
Executors.defaultThreadFactory(), defaultHandler);
}
public ThreadPoolExecutor(int corePoolSize,
int maximumPoolSize,
long keepAliveTime,
TimeUnit unit,
BlockingQueue<Runnable> workQueue,
ThreadFactory threadFactory) {
this(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue,
threadFactory, defaultHandler);
}
public ThreadPoolExecutor(int corePoolSize,
int maximumPoolSize,
long keepAliveTime,
TimeUnit unit,
BlockingQueue<Runnable> workQueue,
RejectedExecutionHandler handler) {
this(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue,
Executors.defaultThreadFactory(), handler);
}
public ThreadPoolExecutor(int corePoolS