问题描述在《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(); }@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);}protectedRunnableFuture newTaskFor(Callable callable){ if(callableinstanceofCancellableTask)return((CancellableTask)callable).newTask(); elsereturnsuper.newTaskFor(callable);}}我觉得这段代码有点绕,感觉很不直白,我个人感觉可以换一种方法实现:publicabstractclassSocketUsingTaskextendsFutureTask implementsCallable { @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的最大的优点在哪?为什么要这样实现?因为感觉存在一些多余的操作。谢谢
撒科打诨
蛊毒传说
相关分类