一个利用common-pool.jar实现线程池的例子
工作线程:
public class SimpleThread extends Thread {
private boolean isRunning;
private GenericObjectPool pool;
public boolean getIsRunning() {
return isRunning;
}
public synchronized void setIsRunning(boolean flag) {
isRunning = flag;
if (flag) {
this.notify();
}
}
public void setPool(GenericObjectPool pool) {
this.pool = pool;
}
public SimpleThread() {
isRunning = false;
}
public void destroy() {
System.out.println("destroy中");
this.interrupt();
}
public synchronized void run() {
try {
while (true) {
if (!isRunning) {
this.wait();
} else {
System.out.println(this.getName() + "开始处理");
sleep(5000);
System.out.println(this.getName() + "结束处理");
setIsRunning(false);
try {
pool.returnObject(this);
} catch (Exception ex) {
System.out.println(ex);
}
}
}
} catch (InterruptedException e) {
System.out.println("我被Interrupted了,所以此线程将被关闭");
return;
}
}
}
创建销毁线程池中对象的工厂:
public class MyPoolableObjectFactory implements PoolableObjectFactory {
private boolean isDebug = true;
public Object makeObject() throws Exception {
SimpleThread simpleThread = new SimpleThread();
simpleThread.start();
debug("创建线程:" + simpleThread.getName());
return simpleThread;
}
public void destroyObject(Object obj) throws Exception {
if (obj instanceof SimpleThread) {
SimpleThread simpleThread = (SimpleThread) obj;
debug("销毁线程:" + simpleThread.getName());
simpleThread.destroy();
}
}
public boolean validateObject(Object obj) {
return true;
}
public void activateObject(Object obj) throws Exception {
}
public void passivateObject(Object obj) throws Exception {
}
public void setIsDebug(boolean isDebug) {
this.isDebug = isDebug;
}
public boolean getIsDebug() {
return isDebug;
}
private void debug(String debugInfo) {
if (isDebug) {
System.out.println(debugInfo);
}
}
}
线程池测试类(兼具线程池管理器的功能)
public class TestThreadPool {
public static void main(String[] args) {
MyPoolableObjectFactory factory = new MyPoolableObjectFactory();
GenericObjectPool pool = new GenericObjectPool(factory);
pool.setMaxActive(20); // 能从池中借出的对象的最大数目
pool.setMaxIdle(20); // 池中可以空闲对象的最大数目
pool.setMaxWait(100); // 对象池空时调用borrowObject方法,最多等待多少毫秒
pool.setTimeBetweenEvictionRunsMillis(600000);// 间隔每过多少毫秒进行一次后台对象清理的行动
pool.setNumTestsPerEvictionRun(-1);// -1表示清理时检查所有线程
pool.setMinEvictableIdleTimeMillis(3000);// 设定在进行后台对象清理时,休眠时间超过了3000毫秒的对象为过期
for (int i = 0; i < 20; i++) {
try {
SimpleThread simpleThread = (SimpleThread) pool.borrowObject();
simpleThread.setPool(pool);
simpleThread.setIsRunning(true);
} catch (Exception ex) {
System.out.println(ex);
}
}
try {
Thread.sleep(8000); // 休息一会儿,再使用线程池
} catch (InterruptedException ex1) {
}
for (int i = 0; i < 10; i++) {
try {
SimpleThread simpleThread = (SimpleThread) pool.borrowObject();
simpleThread.setPool(pool);
simpleThread.setIsRunning(true);
} catch (Exception ex) {
System.out.println(ex);
}
}
}
}
来源:
http://hi.baidu.com/mygia/blog/item/a60ebffdec42501a08244d62.html