gpt4 book ai didi

java - Java Concurrency in Practice中 "Using interruption for cancellation"是否有错字

转载 作者:塔克拉玛干 更新时间:2023-11-02 07:59:47 26 4
gpt4 key购买 nike

在 Brian Goetz 等人的 Java Concurrency in Practice 一书中,第 141 页的示例(2006 年):

7.5: Using interruption for cancellation.

class PrimeProducer extends Thread {
}
...
public void cancel() { interrupt(); }

令人困惑的是,书中指出线程应实现中断策略,而可运行/可调用任务应实现取消策略

然而,这里我们在 Thread 对象中使用了一个 cancel() 方法。这是怎么回事?几页之前,使用 cancel() 给出了 Runnable 的示例 (7.1)。对于任务,我希望看到一个符合条件的 interrupt(),如下所示:

public void cancel() { Thread.currentThread().interrupt(); }

额外的、半相关的信息

我正在使用 ExecutorService,所以我处理任务(不是线程——ExecutorService 的线程工厂除外),但我在书中找不到任何可能的 ExecutorService 完全关闭(许多线程)的示例.

我启动和停止任务的方法是:

Map<CancellableRunnable, Future<?>> cancellableFutures = new HashMap<>(); // keep track of refs to tasks for stop()
public void init() {
Future<?> future = myExecutorService.submit(myTask);
cancellableFutures.put(myTask, future);
}

public void stop() {
for (Future task : cancellableFutures.values()) {
task.cancel(true); // also a confusing step. Should it be cancel() on Future or cancel() on task (Runnable/Callable)?
}
}

最佳答案

The confusing thing is that the book states that Threads should implement an Interruption Policy

没错,

class MyThread extends Thread {
@Override
public void interrupt() { ... }
}

while Runnable / Callable tasks should implement a Cancellation Policy.

没错,

// FutureTask = Runnable (for run) + Future<Void> (for cancel(boolean))
class MyTask extends FutureTask<Void> {
@Override
public boolean cancel(boolean mayInterruptIfRunning) { ... }

@Override
public void run() { ... }
}

Yet here we are with a cancel() method inside of a Thread object.

Thread 既是Thread又是Runnable,所以两者都是interrupt(中断this thread)和cancel(取消this任务,当前正在被这个线程运行的任务)应该被定义。

public class Thread implements Runnable { ... }

PrimeProducer 示例有点令人困惑,因为它假定在 PrimeProducer 中定义的任务将在 PrimeProducer 之外使用。

class PrimeProducer extends Thread {

public void run() {
try {
BigInteger p = BigInteger.ONE;
while (!Thread.currentThread().isInterrupted())
queue.put(p = p.nextProbablePrime());
} catch (InterruptedException consumed) {
/* Allow thread to exit */
}
}

public void cancel() { interrupt(); }

}

非常合理和准确,因为我们可以做到

Runnable runnable = new PrimeProducer();
new Thread(runnable).start();

不过这种情况很少见。我们很可能会简单地选择

new PrimeProducer().start();

这将使我们在 runThread.currentThread().isInterrupted()isInterrupted() 中定义的任务具有上下文感知能力意思是一样的。这就是您对 Thread.currentThread().interrupt()interrupt() 的困惑。

关于java - Java Concurrency in Practice中 "Using interruption for cancellation"是否有错字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57769016/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com