• mutech

    10.1小节中(p258-259)这么一段代码
    public class Section01Demo0002 {
    // 创建一个CountDownLatch实例
    private static final j**a.util.concurrent.CountDownLatch countDownLatch = new j**a.util.concurrent.CountDownLatch(2);

    public static void main(String[] args) throws InterruptedException {
        j**a.util.concurrent.ExecutorService executorService = j**a.util.concurrent.Executors.newFixedThreadPool(2);
        // 将线程A添加到线程池
        executorService.submit(() -> {
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            } finally {
                countDownLatch.countDown();
            }
            System.out.println("child threadA over");
        });
        // 将线程B添加到线程池
        executorService.submit(() -> {
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            } finally {
                countDownLatch.countDown();
            }
            System.out.println("child threadB over");
        });
        System.out.println("wait all child thread over");
        // 等待子线程执行完毕
        countDownLatch.await();
        System.out.println("all child thread over");
        executorService.shutdown();
    }
    

    我们本地执行的结果是
    wait all child thread over
    child threadA over
    all child thread over
    child threadB over

    Process finished with exit code 0

    有时也会出现您书中所写的
    wait all child thread over
    child threadB over
    child threadA over
    all child thread over

    Process finished with exit code 0

    子线程执行完countDownLatch.countDown();后它的时间片用完了,主线程获取到了时间片先输出了,然后子线程又获取到了时间片,继续输出,才有了这样结果,应该把System.out.println(“child threadA over”);放到countDownLatch.countDown();前面,虽然能解决,但是也有问题,没阻塞前就被输出了。
    前面的例子也有这样的问题,这两个例子都是同样情况。

    mutech发表于 2019/7/15 1:03:30
    • 翟陆续

      是的,你分析的很对,书中只是写出了一种情况下的结果,这个在新版里面已经修改过了(输出语句放到Thread.sleep(1000);后面)。

      翟陆续发表于 2019/7/19 20:07:54
    • 翟陆续

      @翟陆续 另外这里 System.out.println("child threadA over");意在表述try子线程内任务执行完毕了,并不是说子线程终止了

      翟陆续发表于 2019/7/19 20:09:54
  • 凯凯

    我从当当买了您的书,写的很棒,请问有没有书中例子的源代码呀?

    凯凯发表于 2019/4/8 17:08:18
  • Zn昕

    在书中的147页,对于cachedHoldCounter的描述不准确,书中说是进入重入锁的次数,那数据类型应当与前面对firstReaderHoldCount的类型一致,但是对于cachedHoldCounter是HoldCounter对象,虽然其中有重入的次数,但是也还有线程的Id(tid)

    Zn昕发表于 2019/3/27 10:01:20
  • 翟陆续

    64页代码中static final Unsafe unsafe; 去掉final;代码static final long stateOffset去掉 final

    翟陆续发表于 2019/3/19 12:53:37
  • xiaobaiguo

    有没有随书代码呀?

    xiaobaiguo发表于 2019/2/19 9:33:36
  • 1
  • 2
  • 3
  • 4
  • 5