import java.util.LinkedList;
import java.util.concurrent.CountDownLatch;
import org.apache.log4j.Logger;
/**
* 線程池是一組線程,限制執行任務的線程數
*/
public class ThreadPool extends ThreadGroup {
private static final Logger logger = Logger.getLogger(ThreadPool.class);
private boolean isAlive;
private LinkedList taskQueue;
private int threadID;
private static int threadPoolID;
private CountDownLatch latch; //聲明計數器
/**
* 創建新的線程池,numThreads是池中的線程數
*/
public ThreadPool(int numThreads) {
super("ThreadPool-" + (threadPoolID++));
setDaemon(true);
isAlive = true;
taskQueue = new LinkedList();
latch = new CountDownLatch(numThreads);
for (int i=0; i<numThreads; i++) {
new PooledThread().start();
}
}
/**
* 請求新任務。人物在池中下一空閒線程中運行,任務按收到的順序執行
*/
public synchronized void runTask(Runnable task) {
if (!isAlive) {
throw new IllegalStateException();//線程被關則拋出IllegalStateException異常
}
if (task != null) {
taskQueue.add(task);
notify();
}
}
protected synchronized Runnable getTask()
throws InterruptedException
{
while (taskQueue.size() == 0) {
if (!isAlive) {
return null;
}
wait();
}
return (Runnable)taskQueue.removeFirst();
}
/**
關閉線程池,所有線程停止,不再執行任務
*/
public synchronized void close() {
if (isAlive) {
isAlive = false;
taskQueue.clear();
//interrupt();
destroy();
}
}
/**
關閉線程池並等待所有線程完成,執行等待的任務
*/
public void join() {
//告訴等待線程線程池已關
synchronized (this) {
isAlive = false;
notifyAll();
}
try {
latch.await();
} catch (Exception e) {
e.printStackTrace();
}
// 等待所有線程完成
// Thread[] threads = new Thread[activeCount()];
// int count = enumerate(threads);
// long s1 = System.currentTimeMillis();
// logger.info("join start....");
// for (int i=0; i<count; i++) {
// try {
// threads[i].join();
// }
// catch (InterruptedException ex) { }
// }
// long s2 = System.currentTimeMillis();
// logger.info("join end...."+(s2-s1)+"ms");
}
private class PooledThread extends Thread {
public PooledThread() {
super(ThreadPool.this,
"PooledThread-" + (threadID++));
}
public void run() {
while (!isInterrupted()) {
// 得到任務
Runnable task = null;
try {
task = getTask();
}
catch (InterruptedException ex) { }
// 若getTask()返回null或中斷,則關閉此線程並返回
if (task == null) {
return;
}
// 運行任務,吸收異常
try {
task.run();
}
catch (Throwable t) {
uncaughtException(this, t);
} finally{
latch.countDown();
}
}
}
}
}
調用
ThreadPool threadPool = null;
threadPool = new ThreadPool(numThreads);
for(int i=0;i<numThreads;i++){
try {
threadPool.runTask(createTask(queueObj.getZpmc(),queueObj.getpFaceInfos()[i],queueObj.getImage(),""+i));
} catch (Exception e) {
logger.info(queueObj.getZpmc());
e.printStackTrace();
}
}
//關閉線程池並等待所有任務完成
threadPool.join();
threadPool.close();
threadPool = null;
private Runnable createTask(final String zpmc,final HWFaceRecGpuSDK.HWFaceInfo hwFaceInfo,final BufferedImage image, final String info) {
return new Runnable() {
public void run() {
try {
cutFace(zpmc,hwFaceInfo,image,info);
} catch (Exception e) {
e.printStackTrace();
}
}
};
}