为了避免系统频繁地创建和销毁线程,可以采用线程池让创建的线程进行复用。在线程池中,有几个活跃线程,当需要使用线程时,可以从池子中拿一个空闲线程,当完成工作时,将这个线程退回到线程池,方便他人使用。
JDK对线程池的支持
ThreadPoolExecutor表示一个线程池,Executors表示线程池工厂,通过Executors可以取得一个拥有特定功能的线程池。主要有:
就看一下其中的固定大小的线程池 newFixedThreadPool()
线程池的使用:
public class ThreadPoolDemo {
public static class MyTask implements Runnable {
@Override
public void run() {
System.out.println(System.currentTimeMillis() + "Thread ID:" + Thread.currentThread().getId());
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
public static void main(String[] args) {
MyTask myTask = new MyTask();
ExecutorService executorService = Executors.newFixedThreadPool(8);//创建固定大小的线程池,内有8个线程
for (int i = 0; i < 10; i++) {
executorService.submit(myTask);//一次向线程池提交10个任务
}
}
}
运行后,线程池就会安排调度这10个任务
结果:
1513158071724Thread ID:12
1513158071724Thread ID:16
1513158071724Thread ID:18
1513158071724Thread ID:13
1513158071724Thread ID:17
1513158071724Thread ID:15
1513158071724Thread ID:14
1513158071724Thread ID:11
1513158072724Thread ID:14
1513158072724Thread ID:13
查看源码
/**
* Creates a thread pool that reuses a fixed number of threads
* operating off a shared unbounded queue. At any point, at most
* {@code nThreads} threads will be active processing tasks.
* If additional tasks are submitted when all threads are active,
* they will wait in the queue until a thread is available.
* If any thread terminates due to a failure during execution
* prior to shutdown, a new one will take its place if needed to
* execute subsequent tasks. The threads in the pool will exist
* until it is explicitly {@link ExecutorService#shutdown shutdown}.
*
* @param nThreads the number of threads in the pool
* @return the newly created thread pool
* @throws IllegalArgumentException if {@code nThreads <= 0}
*/
public static ExecutorService newFixedThreadPool(int nThreads) {
return new ThreadPoolExecutor(nThreads, nThreads,
0L, TimeUnit.MILLISECONDS,
new LinkedBlockingQueue<Runnable>());
}
public ThreadPoolExecutor(int corePoolSize,
int maximumPoolSize,
long keepAliveTime,
TimeUnit unit,
BlockingQueue<Runnable> workQueue,
ThreadFactory threadFactory,
RejectedExecutionHandler handler)
corePoolSize:线程池中的线程数量
maximumPoolSize:最大线程数量
keepAliveTime:当前线程池线程数量超过corePoolSize时,多余的空闲线程的存活时间
unit:keepAliveTime的单位
workQueue:任务队列,被提交但尚未被执行的任务
threadFactory:线程工厂,用于创建线程,一般默认
handler:拒绝策略
workQueue
是一个BlockingQueue接口的对象,用于存放Runnable对象。在ThreadPoolExecutor的构造函数中可以使用一下几种BlockingQueue
- 直接提交队列:SynchronousQueue,提交的任务不会被真实的保存,而将新任务交给线程执行,若没有空闲的进程,则尝试创建新的进程,如果进程数量已经达到最大值,则执行局决策策略,因此一般需要设置很大的maximumPoolSize,否则容易执行拒绝策略
- 有界的任务队列:ArrayBlockingQueue
public ArrayBlockingQueue(int capacity)
如果线程池的实际线程数小于corePoolSize,则会优先创建新的线程,若大于corePoolSize,则会讲新任务加入等待队列,若等待队列已满,无法加入,则在总线程数不大于maximumPoolSize下,创建新的进程执行任务,若大于maximumPoolSize,执行拒绝策略 - 无界的任务队列:LinkedBlockingQueue,当有新的任务到来,系统的线程数小于corePoolSize,线程池会生成新的线程执行任务,当系统的线程数达到corePoolSize时,又有新的任务加入,又没有空闲的线程资源,任务直接进入队列等待。
优先任务队列:PriorityuBlockingQueue,特殊的无界队列,可以根据任务自身的优先级顺序先后执行
ThreadPoolExecutor任务调度逻辑
扩展线程池
ThreadPoolExecutor是可以扩展的线程池,提供了beforeExecute()、afterExecute()、terminated()