问题描述
在《Java并发编程实战》第7章,作者通过newTaskFor方法封装实现了线程的取消。给出的demo如下:
public abstract class SocketUsingTask implements CancellableTask {
@GuardedBy("this") private Socket socket;
protected synchronized void setSocket(Socket s) {
socket = s;
}
public synchronized void cancel() {
try {
if (socket != null)
socket.close();
} catch (IOException ignored) {
}
}
public RunnableFuture newTask() {
return new FutureTask(this) {
public boolean cancel(boolean mayInterruptIfRunning) {
try {
SocketUsingTask.this.cancel();
} finally {
return super.cancel(mayInterruptIfRunning);
}
}
};
}
}
interface CancellableTask extends Callable {
void cancel();
RunnableFuture newTask();
}
@ThreadSafe
class CancellingExecutor extends ThreadPoolExecutor {
public CancellingExecutor(int corePoolSize, int maximumPoolSize, long keepAliveTime, TimeUnit unit, BlockingQueue workQueue) {
super(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue);
}
public CancellingExecutor(int corePoolSize, int maximumPoolSize, long keepAliveTime, TimeUnit unit, BlockingQueue workQueue, ThreadFactory threadFactory) {
super(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue, threadFactory);
}
public CancellingExecutor(int corePoolSize, int maximumPoolSize, long keepAliveTime, TimeUnit unit, BlockingQueue workQueue, RejectedExecutionHandler handler) {
super(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue, handler);
}
public CancellingExecutor(int corePoolSize, int maximumPoolSize, long keepAliveTime, TimeUnit unit, BlockingQueue workQueue, ThreadFactory threadFactory, RejectedExecutionHandler handler) {
super(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue, threadFactory, handler);
}
protected RunnableFuture newTaskFor(Callable callable) {
if (callable instanceof CancellableTask)
return ((CancellableTask) callable).newTask();
else
return super.newTaskFor(callable);
}
}
我觉得这段代码有点绕,感觉很不直白,我个人感觉可以换一种方法实现:
public abstract class SocketUsingTask extends FutureTask implements Callable {
@GuardedBy("this") private Socket socket;
protected synchronized void setSocket(Socket s) { socket = s; }
public synchronized void cancel() {
try {
if (socket != null)
socket.close();
} catch (IOException ignored) { }
}
@Override
public boolean cancel(boolean mayInterruptIfRunning) {
try {
cancel();
} finally {
return super.cancel(mayInterruptIfRunning);
}
}
}
我想知道《Java并发编程实战》中给出的这个demo的最大的优点在哪?为什么要这样实现?因为感觉存在一些多余的操作。谢谢