ThreadPoolExecutor的afterExecution方法之我见
对于ThreadPoolExecutor的
protected void afterExecute(Runnable r, Throwable t)
方法从字面上以及doc上看有点模糊(也许是偶的E文很烂),所以想动手写写,代码如下:
import java.util.ArrayList;import java.util.List;import java.util.concurrent.BlockingQueue;import java.util.concurrent.Callable;import java.util.concurrent.Future;import java.util.concurrent.LinkedBlockingQueue;import java.util.concurrent.ThreadPoolExecutor;import java.util.concurrent.TimeUnit;public class TestThreadPool {/** * @param args */public static void main(String[] args) {ThreadPoolExecutor2 pool = new ThreadPoolExecutor2(5, 5, 0L, TimeUnit.MILLISECONDS, new LinkedBlockingQueue<Runnable>());List<Callable<Integer>> list = new ArrayList<Callable<Integer>>(); list.add(new Runner()); list.add(new Runner()); list.add(new Runner()); list.add(new Runner()); list.add(new Runner()); list.add(new Runner()); list.add(new Runner()); list.add(new Runner()); list.add(new Runner()); List<Future<Integer>> taskList = null; try {taskList = pool.invokeAll(list);} catch (InterruptedException e) {e.printStackTrace();} finally {if(taskList != null) {for(Future<Integer> future: taskList) {System.out.println(future.cancel(true));}}pool.shutdown();} }private static class Runner implements Callable<Integer> {@Overridepublic Integer call() throws Exception {try {Thread.sleep(10000);} catch (InterruptedException e) {e.printStackTrace();}return 0;}}private static class ThreadPoolExecutor2 extends ThreadPoolExecutor {public ThreadPoolExecutor2(int corePoolSize, int maximumPoolSize,long keepAliveTime, TimeUnit unit,BlockingQueue<Runnable> workQueue) {super(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue);}@Overrideprotected void afterExecute(Runnable r, Throwable t) {super.afterExecute(r, t);System.out.println(Thread.currentThread().getName());System.out.println(this.getActiveCount());}}}