一种最为简单的线程创建和回收的方法:
new Thread(new Runnable(){
@Override
public void run() {
while(true)
{
try {
Thread.sleep(1000);//休息1s
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}).start();
在run结束后,自动回收该线程 。但在真实生产环境中,可能会开启多个线程来支撑应用系统。创建和关闭都需要花费时间,并且再生产环境中,线程的数量必须合理控制,盲目的大量创建线程,对系统性能是有伤害的。为了节省多线程并发时不断创建和销毁线程所带来的额外开销,引入线程池。
线程池的基本功能就是对线程进行复用。当接收一个任务等待处理时,先去线程池中查找是否有空闲线程,没有再创建新的线程;并且执行完毕后,将新建的线程放入线程池的空闲队列备用,而不直接销毁。
1、创建一个简易线程池
ThreadPool类:提供线程池创建、停止、添加线程、执行任务等方法
public class ThreadPool {
private static ThreadPool instance=null;
//空闲的县城队列
private List<PThread> idleThreads;
//已有的线程数
private int count;
private boolean isShutDown=false;
private ThreadPool()
{
this.idleThreads=new Vector(5);//类似于Arraylist
count=0;
}
public int getCreatedThread()
{
return count;
}
//取得线程实例
public synchronized static ThreadPool getInstance()
{
if(instance==null)
instance=new ThreadPool();
return instance;
}
//将线程放入线程池
public synchronized void putThread(PThread putThread)
{
if(!isShutDown)
{
idleThreads.add(putThread);
}else
{
putThread.shutDown();
}
}
//停止池中的所有线程
public synchronized void shotdown()
{
isShutDown=true;
for(int threadIndex=0;threadIndex<idleThreads.size();threadIndex++)
{
PThread idelThread=(PThread)idleThreads.get(threadIndex);
idelThread.shutDown();
}
}
//执行任务
public synchronized void start()
{
PThread thread=null;
//如果有空闲线程,直接使用
if(idleThreads.size()>0)
{
int lastIndex=idleThreads.size()-1;