/**
* 2010-8-3 下午09:14:29
* @auth cjj
*/
package org.prime.threadpool;
import java.util.Queue;
import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.concurrent.atomic.AtomicInteger;
/**
* @author cjj
*
*/
public class CPrimePool {
private Object lock = new Object();
private volatile boolean stop = false;
private int coreSize;
private int maxSize;
private AtomicInteger curThreadCount = new AtomicInteger();
private Queue<WorkThread> cacheThreads = new ConcurrentLinkedQueue<WorkThread>();
public CPrimePool() {
init();
}
public CPrimePool(int coreSize, int maxSize) {
this.coreSize = coreSize;
this.maxSize = maxSize;
init();
}
private void init() {
if (coreSize == 0) {
coreSize = 1;
}
if (maxSize == 0) {
maxSize = Runtime.getRuntime().availableProcessors() + 1;
}
}
public void runTask(Runnable task) {
if (!stop) {
if (curThreadCount.get() < coreSize) {
WorkThread work = new WorkThread();
int i = curThreadCount.getAndIncrement();
work.setName("Work Thread : "+i);
work.start();
work.setTask(task);
} else {
WorkThread work = cacheThreads.poll();
if (work != null) {
work.setTask(task);
} else {
if (curThreadCount.get() < maxSize) {
work = new WorkThread();
int i = curThreadCount.getAndIncrement();
work.setName("Work Thread : "+i);
work.start();
work.setTask(task);
} else {
synchronized (lock) {
while ((work = cacheThreads.poll()) == null
&& !stop) {
try {
lock.wait();
} catch (InterruptedException e) {
// ignore
}
}
}
if (!stop) {
work.setTask(task);
}
}
}
}
}
}
public void stop() {
stop = true;
WorkThread work = null;
while ((work = cacheThreads.poll()) != null) {
work.interrupt();
}
}
private class WorkThread extends Thread {
private Runnable task;
public void setTask(Runnable task) {
synchronized (this) {
this.task = task;
notifyAll();
}
}
@Override
public void run() {
while (!stop) {
try {
if (task != null) {
task.run();
}
synchronized (lock) {
task = null;
// 回收
cacheThreads.add(this);
lock.notifyAll();
}
synchronized (this) {
while (task == null && !stop) {
wait();
}
}
} catch (InterruptedException ie) {
break;
}
}
}
}
}
使用示例代码:
/**
* 2010-8-3 下午11:31:28
* @auth cjj
*/
package org.prime.threadpool.test;
import org.prime.threadpool.CPrimePool;
/**
* @author cjj
*
*/
public class Test {
/**
* @param args
* @throws InterruptedException
*/
public static void main(String[] args) throws InterruptedException {
CPrimePool pool = new CPrimePool();
for (int i = 0; i < 500000; i++) {
pool.runTask(new MyThread(i));
}
// Thread.sleep(30000);
pool.stop();
}
static class MyThread implements Runnable {
private int i;
public MyThread(int i) {
this.i = i;
}
@Override
public void run() {
for (int i = 0; i < Integer.MAX_VALUE; i++) {
System.out.println("thread:" + i);
}
}
}
}