Java 并发实践——代码 list 5.11

标签 java concurrency

在 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/

相关文章:

java - 用 Espresso 测试 recyclerView,如何执行点击或断言

java - 从构造函数调用抽象方法的安全替代方案

java - 通过派生类访问Java中定义的静态内部类

c++ - 了解 C++ 中放宽的内存顺序

c# - 并发字典 : How do I add if value does not exist or condition fails?

Java EE并发问题

java - 如何在 Java 中打印 unicode 字符串?

java - quartz 工作比。立即执行一次性任务的线程

java - 自定义 future 对象

java - 带参数的并发 JUnit 测试