package com.zte.pub.common.util;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.RejectedExecutionHandler;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
/**
* 线程池概念实现批处理
* (如果不需要主线程等待任务处理,则直接使用ThreadPoolExecutor类即可)
*
*/
public class EtcThreadPoolExecutor extends ThreadPoolExecutor {
private boolean runnning = false;//线程池状态
private boolean hasFinish = false;//是否全部完成
public EtcThreadPoolExecutor(int corePoolSize, int maximumPoolSize, long keepAliveTime, TimeUnit unit, BlockingQueue<Runnable> workQueue, RejectedExecutionHandler handler) {
super(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue, handler);
}
@Override
protected void afterExecute(Runnable r, Throwable t) {
super.afterExecute(r, t);
synchronized (this) {
if (this.getActiveCount() == 1)// 已执行完任务之后的最后一个线程
{
this.hasFinish = true;
this.notify();//全部结束后,唤醒主线程
}
}
}
public void isEndTask() throws InterruptedException {
synchronized (this) {
while (this.hasFinish == false) {
this.wait();//让主线程休眠
}
this.hasFinish = false;//复位状态,否则下次执行直接退出
this.runnning = false;//线程池置闲
}
}
public boolean isRunnning() {
return runnning;
}
public void busyRunnning() {
this.runnning = true;//线程池置忙
}
}
Thanks!
Best regards!