3
在JCiP書籍中,listing 5.11,如果Thread t
中的任何一個被中斷(因爲startGate.await()
可以拋出InterruptedException
),這個代碼將永遠等待,因此endGate鎖定永遠不會被釋放?實踐中的Java併發 - 列表5.11
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;
}}
你爲什麼不先_try_? – mre 2011-05-04 18:34:47
sthupahsmaht,無論他是否嘗試。考慮到它正在被廣泛使用和被高度引用的書中出版,這是一個有效的問題。 – 2011-05-04 18:47:09
是的,我試過了,它等待。仍然不能相信這本書是否存在,希望有人能解釋我錯了 – robinmag 2011-05-04 18:51:58