跪求!《Java并发编程实战》使用newTaskFor实现线程取消的疑惑求解答!

问题描述
在《Java并发编程实战》第7章,作者通过newTaskFor方法封装实现了线程的取消。给出的demo如下:
publicabstractclassSocketUsingTaskimplementsCancellableTask{
@GuardedBy("this")privateSocketsocket;
protectedsynchronizedvoidsetSocket(Sockets){
socket=s;
}
publicsynchronizedvoidcancel(){
try{
if(socket!=null)
socket.close();
}catch(IOExceptionignored){
}
}
publicRunnableFuturenewTask(){
returnnewFutureTask(this){
publicbooleancancel(booleanmayInterruptIfRunning){
try{
SocketUsingTask.this.cancel();
}finally{
returnsuper.cancel(mayInterruptIfRunning);
}
}
};
}
}
interfaceCancellableTaskextendsCallable{
voidcancel();
RunnableFuturenewTask();
}
@ThreadSafe
classCancellingExecutorextendsThreadPoolExecutor{
publicCancellingExecutor(intcorePoolSize,intmaximumPoolSize,longkeepAliveTime,TimeUnitunit,BlockingQueueworkQueue){
super(corePoolSize,maximumPoolSize,keepAliveTime,unit,workQueue);
}
publicCancellingExecutor(intcorePoolSize,intmaximumPoolSize,longkeepAliveTime,TimeUnitunit,BlockingQueueworkQueue,ThreadFactorythreadFactory){
super(corePoolSize,maximumPoolSize,keepAliveTime,unit,workQueue,threadFactory);
}
publicCancellingExecutor(intcorePoolSize,intmaximumPoolSize,longkeepAliveTime,TimeUnitunit,BlockingQueueworkQueue,RejectedExecutionHandlerhandler){
super(corePoolSize,maximumPoolSize,keepAliveTime,unit,workQueue,handler);
}
publicCancellingExecutor(intcorePoolSize,intmaximumPoolSize,longkeepAliveTime,TimeUnitunit,BlockingQueueworkQueue,ThreadFactorythreadFactory,RejectedExecutionHandlerhandler){
super(corePoolSize,maximumPoolSize,keepAliveTime,unit,workQueue,threadFactory,handler);
}
protectedRunnableFuturenewTaskFor(Callablecallable){
if(callableinstanceofCancellableTask)
return((CancellableTask)callable).newTask();
else
returnsuper.newTaskFor(callable);
}
}
我觉得这段代码有点绕,感觉很不直白,我个人感觉可以换一种方法实现:
publicabstractclassSocketUsingTaskextendsFutureTaskimplementsCallable{
@GuardedBy("this")privateSocketsocket;
protectedsynchronizedvoidsetSocket(Sockets){socket=s;}
publicsynchronizedvoidcancel(){
try{
if(socket!=null)
socket.close();
}catch(IOExceptionignored){}
}
@Override
publicbooleancancel(booleanmayInterruptIfRunning){
try{
cancel();
}finally{
returnsuper.cancel(mayInterruptIfRunning);
}
}
}
我想知道《Java并发编程实战》中给出的这个demo的最大的优点在哪?为什么要这样实现?因为感觉存在一些多余的操作。谢谢
慕后森
浏览 583回答 2
2回答

撒科打诨

像这样的类似问题可以提很多,比如ArrayList为什么要继承List接口,直接继承Collection接口也能直接实现软件工程有一些很重要的实践原则,比如开闭原则,决定了你的代码的扩展性如何,一开始不理解是很正常的,都是实践的经验。项目又不是能完成当时的需求即可,还需要考虑的后期的扩展和维护的

蛊毒传说

我觉得demo的写法有2点:第一demo把Callable重新用CancellableTask扩展了一下,如果你要增加新的功能就可以做到面向接口编程的效果,你直接实现了扩展性肯定没这个好;第二我看newTaskFor那个就是生成RunnableFuture的工厂,这个demo中貌似没有用到
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript