package canceltask;
import java.util.concurrent.Callable;
import java.util.concurrent.RunnableFuture;
/**
* 接口:封装一个取消任务
* */
public interface CancellableTask<T> extends Callable {
// 取消
void cancel();
// 新任务,返回RunnableFuture
RunnableFuture<T> newTask();
}
package canceltask;
import java.io.IOException;
import java.net.Socket;
import java.util.concurrent.FutureTask;
import java.util.concurrent.RunnableFuture;
/**
* 实现取消任务的抽象类
* */
public abstract class SocketUsingTask<T> implements CancellableTask {
private Socket socket;
protected synchronized void setSocket (Socket s) {
this.socket = s;
}
// 实现取消任务的方法,socket可通过关闭底层套接字,实现中断
public synchronized void cancel () {
if (socket == null) {
try {
// 关闭套接字,使执行write,read方法而被阻塞的线程抛出SocketException
socket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
// 新建任务
@Override
public RunnableFuture newTask() {
// 推荐使用:本类中重写方法,任何在return时(或其他情况下)调用重写的方法,很巧妙
return new FutureTask<T>(this) {
// 重写FutureTask中的cancel方法
public boolean cancel(boolean mayInterruptIfRunning) {
try {
// 类名.this:类的对象
// 1.调用cancel方法,关闭套接字连接,这时cancel方法抛出异常没事。
SocketUsingTask.this.cancel();
} finally {
// 2.使用FutureTask取消任务
return super.cancel(mayInterruptIfRunning);
}
}
};
}
}
package canceltask;
import java.util.concurrent.*;
public class CancellingExecutor extends ThreadPoolExecutor {
public CancellingExecutor(int corePoolSize, int maximumPoolSize, long keepAliveTime, TimeUnit unit, BlockingQueue<Runnable> workQueue) {
super(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue);
}
public CancellingExecutor(int corePoolSize, int maximumPoolSize, long keepAliveTime, TimeUnit unit, BlockingQueue<Runnable> workQueue, ThreadFactory threadFactory) {
super(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue, threadFactory);
}
public CancellingExecutor(int corePoolSize, int maximumPoolSize, long keepAliveTime, TimeUnit unit, BlockingQueue<Runnable> workQueue, RejectedExecutionHandler handler) {
super(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue, handler);
}
public CancellingExecutor(int corePoolSize, int maximumPoolSize, long keepAliveTime, TimeUnit unit, BlockingQueue<Runnable> workQueue, ThreadFactory threadFactory, RejectedExecutionHandler handler) {
super(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue, threadFactory, handler);
}
// 创建任务
protected<T> RunnableFuture<T> newTaskFor (Callable<T> callable) {
if (callable instanceof CancellableTask) {
return ((CancellableTask) callable).newTask();
} else {
return super.newTaskFor(callable);
}
}
// 模拟测试方法
public void test () throws InterruptedException {
RunnableFuture<Integer> tt = newTaskFor(new Callable<Integer>() {
@Override
public Integer call() throws Exception {
for (int i = 0; i < 200000; i++) {
System.out.println(i+ ", ");
}
return 1;
}
});
Thread.sleep(1);
tt.cancel(true);
}
}