为了账号安全,请及时绑定邮箱和手机立即绑定

跪求!newTaskFor实现线程取消的疑惑感激不尽

跪求!newTaskFor实现线程取消的疑惑感激不尽

幕布斯6054654 2019-06-12 09:02:02
看书,有个情况如下:通过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();}@ThreadSafeclassCancellingExecutorextendsThreadPoolExecutor{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();elsereturnsuper.newTaskFor(callable);}}我觉得这段代码有点绕,感觉很不直白,我个人感觉可以换一种方法实现:publicabstractclassSocketUsingTaskextendsFutureTaskimplementsCallable{@GuardedBy("this")privateSocketsocket;protectedsynchronizedvoidsetSocket(Sockets){socket=s;}publicsynchronizedvoidcancel(){try{if(socket!=null)socket.close();}catch(IOExceptionignored){}}@Overridepublicbooleancancel(booleanmayInterruptIfRunning){try{cancel();}finally{returnsuper.cancel(mayInterruptIfRunning);}}}我想知道《Java并发编程实战》中给出的这个demo的最大的优点在哪?为什么要这样实现?因为感觉存在一些多余的操作。谢谢
查看完整描述

2 回答

?
小怪兽爱吃肉

TA贡献1852条经验 获得超1个赞

我觉得demo的写法有2点:第一demo把Callable重新用CancellableTask扩展了一下,如果你要增加新的功能就可以做到面向接口编程的效果,你直接实现了扩展性肯定没这个好;第二我看newTaskFor那个就是生成RunnableFuture的工厂,这个demo中貌似没有用到
                            
查看完整回答
反对 回复 2019-06-12
  • 2 回答
  • 0 关注
  • 342 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信