版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/tomorrow_fine/article/details/80465525
为了节省系统在并发时不断创建和销毁线程所带来的额外开销,就需要引入线程池。线程池的基本思想是,线程使用完后并不销毁,而是一直处于等待状态,如果下一个任务进入,可以再使用这个线程执行,这样就减少了线程的创建和销毁。
首先是线程池的实现:
package com.mr.smart.future.simplethreadpool;
import java.util.List;
import java.util.Vector;
public class ThreadPool {
private static ThreadPool instance = null;
//空闲的线程队列
private List<PThread> idleThreads;
//已有的线程总数
private int threadCounter;
private boolean isShutDown = false;
private ThreadPool() {
this.idleThreads = new Vector<>(5);
threadCounter = 0;
}
public int getThreadCounter() {
return threadCounter;
}
//取得线程池的实例
public synchronized static ThreadPool getInstance() {
if (instance == null)
instance = new ThreadPool();
return instance;
}
//将线程放入池中
protected synchronized void repool(PThread repoolingThread) {
if (!isShutDown) {
idleThreads.add(repoolingThread);
} else {
repoolingThread.shutDown();
}
}
//停止池中所有线程
public synchronized void shutDown() {
isShutDown = true;
for (int threadIndex = 0; threadIndex < idleThreads.size(); threadIndex++) {
PThread idleThread = idleThreads.get(threadIndex);
idleThread.shutDown();
}
}
//执行任务
public synchronized void start(Runnable target) {
PThread thread = null;
if (idleThreads.size() > 0) {
int lastIndex = idleThreads.size() - 1;
thread = (PThread) idleThreads.get(lastIndex);
idleThreads.remove(lastIndex);
//立即执行这个任务
thread.setTarget(target);
} else {
threadCounter++;
thread = new PThread(target, "PThread #" + threadCounter, this);
// 启动这个线程
thread.start();
}
}
}
配合线程:
package com.mr.smart.future.simplethreadpool;
public class PThread extends Thread {
//线程池
private ThreadPool pool;
//任务
private Runnable target;
private boolean isShutDown = false;
private boolean isIdle = false;
//构造函数
public PThread(Runnable target, String name, ThreadPool pool) {
super(name);
this.pool = pool;
this.target = target;
}
public Runnable getTarget() {
return target;
}
public boolean isIdle() {
return isIdle;
}
@Override
public void run() {
//只要没有关闭,则一直不结束该线程
while (!isShutDown) {
isIdle = false;
if (target != null) {
//运行任务
target.run();
}
//任务结束了,到闲置状态
isIdle = true;
try {
//该任务结束后,不关闭线程,而是放入线程池空闲队列
pool.repool(this);
synchronized (this) {
//线程空闲,等待新的任务到来
wait();
}
} catch (InterruptedException e) {
}
isIdle = false;
}
}
public synchronized void setTarget(Runnable newTarget) {
target = newTarget;
notifyAll();
}
//关闭线程
public synchronized void shutDown() {
isShutDown = true;
notifyAll();
}
}