局限性:showdownNow会尝试取消正在执行的任务并返回所有已经提交但尚未开始执行的任务。也就是说我们不能了解到哪些任务已经开始但是尚未结束的任务,那么这些任务有可能就被丢弃了。
解决办法如下:
思路:判断任务在返回时是否处于中断状态,如果处于中断转态,我们将这些任务的线程存放到集合中。
代码:
public class TrackingExecutor extends AbstractExecutorService{
private final ExecutorService exe;
private final Set<Runnable> tasksCancelledAtShutdown =
Collections.synchronizedSet(new HashSet<Runnable>());
public TrackingExecutor(ExecutorService exec) {
this.exe = exec;
}
@Override
public void shutdown() {
exe.shutdown();
}
@Override
public List<Runnable> shutdownNow() {
return exe.shutdownNow();
}
@Override
public boolean isShutdown() {
return exe.isShutdown();
}
@Override
public boolean isTerminated() {
return exe.isTerminated();
}
@Override
public boolean awaitTermination(long timeout, TimeUnit unit) throws InterruptedException {
return exe.awaitTermination(timeout, unit);
}
@Override
public void execute(Runnable runnable) {
exe.execute(new Runnable() {
@Override
public void run() {
try {
runnable.run();
}finally {
if (isShutdown() && Thread.currentThread().isInterrupted()) {
tasksCancelledAtShutdown.add(runnable);//将 取消正在执行的任务存放到set中
}
}
}
});
}
//获取取消的线程
public List<Runnable> getCancelledTask(){
if (!exe.isTerminated()) {
throw new IllegalStateException();
}
return new ArrayList<Runnable>(tasksCancelledAtShutdown);
}
}