在 JCiP 书中,位于 listing 5.11 , 如果 Thread t
中的任何一个被中断,这段代码是否会永远等待(因为 startGate.await()
可以抛出 InterruptedException
)所以 endGate latch 将永远不会被释放?
public class TestHarness {
public long timeTasks(int nThreads, final Runnable task)
throws InterruptedException {
final CountDownLatch startGate = new CountDownLatch(1);
final CountDownLatch endGate = new CountDownLatch(nThreads);
for (int i = 0; i < nThreads; i++) {
Thread t = new Thread() {
public void run() {
try {
startGate.await();
try {
task.run();
} finally {
endGate.countDown();
}
} catch (InterruptedException ignored) { }
}
};
t.start();
}
long start = System.nanoTime();
startGate.countDown();
endGate.await();
long end = System.nanoTime();
return end-start;
}}
最佳答案
你没有看错。该代码实际上会挂起。请记住,他们编写的许多代码示例都是为了让读者了解代码片段在功能上应该做什么。他们不打算让开发人员在未经测试的情况下开箱即用地使用他们的代码。
例如,有人询问有关创建自填充缓存的问题。有人指出了 JCiP 中的 Memoizer 部分,其中 Tim Peierls 紧随其后:
The Memoizer class presented in that section is only to illustrate a technique. It lacks a number of useful features, and it is nowhere near production-ready.
Use MapMaker anywhere you might have been tempted to use or adapt Memoizer.
http://old.nabble.com/How-to-implement-a-self-populating-memoizer-cache--td30121001.html
关于Java 并发实践——代码 list 5.11,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5888176/