public interface CancellableTask<T> extends Callable<T>{
void cancel();
RunnableFuture<T> newTask();
}
public class CancellingExecutor extends ThreadPoolExecutor{
...
protected<T> RunnableFuture<T> newTaskFor(Callable<T> callable){
if(callable instanceof CancellableTask){
return (CancellableTask<T>).newTask();
}else{
return super.newTaskFor(callable);
}
}
}
public abstract class SocketUsingTask<T> implements CancellableTask<T>{
private Socket socket;
public synchronized void setSocket(Socket s){
socket = s;
}
public synchronized void cancel(){
try{
if(socket != null){
socket.close();
}
}catch(IOException ignored){}
}
public RunnableFuture<T> newTask(){
return new FutureTask<T>(this){
public boolean cancel(boolean mayInterruptIfRunning){
try{
SocketUsingTask.this.cancel();
}finally{
return super.cancel(mayInterruptIfRunning);
}
}
}
}
}
通过newTaskFor将非标准取消封装任务
最新推荐文章于 2023-06-21 16:25:32 发布