看書,有個(gè)情況如下:通過newTaskFor方法封裝實(shí)現(xiàn)了線程的取消。給出的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);}}我覺得這段代碼有點(diǎn)繞,感覺很不直白,我個(gè)人感覺可以換一種方法實(shí)現(xiàn):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并發(fā)編程實(shí)戰(zhàn)》中給出的這個(gè)demo的最大的優(yōu)點(diǎn)在哪?為什么要這樣實(shí)現(xiàn)?因?yàn)楦杏X存在一些多余的操作。謝謝
跪求!newTaskFor實(shí)現(xiàn)線程取消的疑惑感激不盡
幕布斯6054654
2019-06-12 09:02:02