线程池的作用有如下两个:
- 在多线程程序中,线程的创建和销毁有很高的代价,因此线程池来分担这一部分性能的损耗。就是说线程池使用场景之一就是当线程的创建和销毁所消耗的时间远大于线程执行任务所消耗的时间。
- 在并发编程实践中提到,单线程程序的缺点就是串行执行效率低,单纯的多线程呢,没法管理多线程的数量。因此折中方式就是线程池了。换句话说,线程池可以广泛的使用在多线程程序中。
线程池的原理是一个线程池对象管理了一个任务队列和一个线程数组,这个任务队列接收外界的任务,线程池对象维护和管理线程数组。
package com.lenovo.pool;
import java.util.LinkedList;
import java.util.List;
public class ThreadPool {
private static int workNum = 5; // the default number of threads in thread array
private static volatile int finishedTask = 0;
private List<Runnable> taskQueue = new LinkedList<Runnable>(); //task queue
private static ThreadPool threadPool;
private WorkThread[] workThreads; // thread array
//default constructor
private ThreadPool(){
this(5);
}
// constructor: to initiate the thread array and start to run the
// thread in thread array.
private ThreadPool(int workNum){
ThreadPool.workNum = workNum;
workThreads = new WorkThread[workNum];
for(int i = 0;i<workNum;i++){
workThreads[i] = new WorkThread();
workThreads[i].start();
}
}
// the method can get the threadPool object
public static ThreadPool getThreadPool(){
return getThreadPool(ThreadPool.workNum);
}
public static ThreadPool getThreadPool(int workNum1){
if(workNum1 <= 0){
workNum1 = ThreadPool.workNum;
}
if(threadPool == null){
threadPool = new ThreadPool(workNum1);
}
return threadPool;
}
// the method to add the task in task queue and notify the taskQueue waiting
public void execute(Runnable task){
synchronized(taskQueue){
taskQueue.add(task);
taskQueue.notify();
}
}
public void execute(Runnable[] task){
synchronized(taskQueue){
for(Runnable t : task){
taskQueue.add(t);
}
taskQueue.notify();
}
}
public int getWorkThreadNumber(){
return workNum;
}
public int getFinishedTaskNumber(){
return finishedTask;
}
// shutdown method
// to stop all the threads in thread array.
// to clear the task queue
public void shutdown(){
while(!taskQueue.isEmpty()){
try {
Thread.sleep(10);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
for(int i=0;i<workNum;i++){
workThreads[i].stopWorker();
workThreads[i] = null;
}
threadPool = null;
taskQueue.clear();
}
// task Object.to run the task
private class WorkThread extends Thread{
private boolean isRunning = true;
@Override
public void run() {
// TODO Auto-generated method stub
super.run();
Runnable r = null;
while(isRunning){
synchronized(taskQueue){
while(isRunning && taskQueue.isEmpty()){
try {
taskQueue.wait(20);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if(!taskQueue.isEmpty()){
r = taskQueue.remove(0);
}
if(r!=null){
r.run();
}
finishedTask ++;
r = null;
}
}
}
public void stopWorker(){
isRunning = false;
}
}
}
线程池对象在构造函数中初始化了一个任务队列和一个Worker数组,worker对象就是一个线程,这个线程持有了一个Runnable对象,并循环检查任务队列中是否有任务,如果没有,则等待。如果任务队列中有任务,则取出这个任务,并交给runnable对象来执行。
Java实现了功能更强大的线程池,但大致原理还是一样。下一次将分析一下java线程池的代码。
另外,这里参考了如下文章:
http://blog.csdn.net/touch_2011/article/details/6914468/