线程池能提高程序的并发能力。也容易导致与线程池有关的死锁、系统资源不足、线程泄漏、并发错误、任务过载等问题。
线程池代码:
package com.lyle.code;
import java.util.LinkedList;
/**
* 线程池
*/
public class ThreadPool extends ThreadGroup {
private boolean isClosed = false; //线程池是否关闭
private LinkedList<Runnable> workQueue; //工作队列
private static int threadPoolId; //线程池ID
private int threadId; //线程ID
public ThreadPool(int poolSize) {
super("ThreadPool-"+(threadPoolId++));
setDaemon(true);
workQueue = new LinkedList<Runnable>();
for(int i=0;i<poolSize;i++){
new WorkThread().start();
}
}
/**
* 向工作队列加入一个新任务,由工作线程去执行该任务
* @param task
*/
public synchronized void execute(Runnable task){
if(isClosed){
throw new IllegalStateException();
}
if(task!=null){
workQueue.add(task);
notify();
}
}
/**
* 从工作队列中取出一个任务,工作线程会调用次方法
* @return
* @throws InterruptedException
*/
private synchronized Runnable getTask() throws InterruptedException {
while(workQueue.size()==0){
if(isClosed){
return null;
}
wait(); //如果队列中没有任务就等待
}
return workQueue.removeFirst();
}
/**
* 关闭线程池
*/
public void close(){
if(!isClosed){
isClosed=true;
workQueue.clear();
interrupt(); //中断所有工作线程,继承自ThreadGroup
}
}
/**
* 等待所有线程把所有任务执行完成
*/
public void join(){
synchronized (this) {
isClosed=true;
notify();
}
Thread[] threads=new Thread[activeCount()];
int count = enumerate(threads);
for(int i=0;i<count;i++){
try{
threads[i].join();
}catch(InterruptedException e){
e.printStackTrace();
}
}
}
/**
* 内部类
*
*/
private class WorkThread extends Thread{
public WorkThread(){
//加入到当前ThreadPool线程组中
super(ThreadPool.this,"WorkThread-"+(threadId++));
}
public void run(){
while(!isInterrupted()){
Runnable task=null;
try {
task=getTask();
} catch (InterruptedException e) {
e.printStackTrace();
}
if(task==null){
return;
}
task.run();
}
}
}
}
测试:
package com.lyle.code;
public class ThreadPoolTest {
/**
* @param args
*/
public static void main(String[] args) {
ThreadPool threadPool=new ThreadPool(8);
for(int i=0;i<15;i++){
threadPool.execute(createTask(i));
}
threadPool.join();
}
private static Runnable createTask(final int task){
return new Runnable() {
public void run() {
System.out.println("Task"+task+":start");
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
}
System.out.println("Task"+task+":end");
}
};
}
}