述
上文提到了线程池的钩子方法,其实就是线程池在执行每个任务的前后执行一些操作,还有线程池的暂停与继续,等等一些辅助功能,下面看一下如何使用
钩子方法的使用
ThreadPoolExecutor
提供了3个钩子方法,需要子类去根据自己的需要重写,三个方法如下:
protected void beforeExecute(Thread t, Runnable r) { } // 任务执行前
protected void afterExecute(Runnable r, Throwable t) { } // 任务执行后
protected void terminated() { } // 线程池执行结束后
所以我们要新建一个类,然后继承 ThreadPoolExecutor
,重写这几个方法
public class PauseableThreadPool extends ThreadPoolExecutor {
public PauseableThreadPool(int corePoolSize, int maximumPoolSize, long keepAliveTime, TimeUnit unit, BlockingQueue<Runnable> workQueue) {
super(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue);
}
public PauseableThreadPool(int corePoolSize, int maximumPoolSize, long keepAliveTime, TimeUnit unit, BlockingQueue<Runnable> workQueue, ThreadFactory threadFactory) {
super(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue, threadFactory);
}
public PauseableThreadPool(int corePoolSize, int maximumPoolSize, long keepAliveTime, TimeUnit unit, BlockingQueue<Runnable> workQueue, RejectedExecutionHandler handler) {
super(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue, handler);
}
public PauseableThreadPool(int corePoolSize, int maximumPoolSize, long keepAliveTime, TimeUnit unit, BlockingQueue<Runnable> workQueue, ThreadFactory threadFactory, RejectedExecutionHandler handler) {
super(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue, threadFactory, handler);
}
private boolean isPausend;
private final ReentrantLock lock=new ReentrantLock();
private final Condition unpaused=lock.newCondition();
@Override
protected void beforeExecute(Thread t, Runnable r) {
super.beforeExecute(t, r);
lock.lock();
try {
//如果是赞停状态 那么将线程暂停
while (isPausend){
unpaused.await();
}
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
lock.unlock();
}
}
/**
* 暂停方法
*/
public void paust(){
lock.lock();
try {
isPausend=true;
}finally {
lock.unlock();
}
}
/**
* 恢复方法
*/
public void resume(){
lock.lock();
try {
isPausend=false;
unpaused.signalAll();
}finally {
lock.unlock();
}
}
@Override
protected void afterExecute(Runnable r, Throwable t) {
super.afterExecute(r, t);
System.out.println("执行了完了一个任务");
}
@Override
protected void terminated() {
super.terminated();
System.out.println("线程池执行完成");
}
}
代码看着比较多,但是很简单, 上面是一堆构造不用管,然后就是个暂停和继续方法, 其实就是操作一个共享变量,然后再每个任务运行之前会调用 beforeExecute()
方法,这个方法会判断暂停状态是否为true, 是的话就阻塞,之后调用了继续的方法后再唤醒继续执行
然后写个main方法去测试一下效果
public static void main(String[] args) throws InterruptedException {
PauseableThreadPool pool=new PauseableThreadPool(10,10,10,TimeUnit.SECONDS,new LinkedBlockingDeque<>());
Runnable runnable = new Runnable(){
@Override
public void run() {
try {
Thread.sleep(100);
System.out.println("我被执行了");
} catch (InterruptedException e) {
e.printStackTrace();
}
}
};
for (int i =0;i<1000;i++){
pool.execute(runnable);
}
Thread.sleep(1000);
pool.paust();
System.out.println("我被暂停了");
Thread.sleep(10000);
pool.resume();
System.out.println("我被恢复了");
}
总结
掌握钩子方法的作用,以及如何实现自定义的钩子方法