java循环new线程_《Java并发编程实战》使用newTaskFor实现线程取消的疑惑

问题描述

在《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的最大的优点在哪?为什么要这样实现?因为感觉存在一些多余的操作。谢谢

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值