【问题标题】:Java CountDownLatch example main thread doesn't wait on latch.awaitJava CountDownLatch 示例主线程不等待latch.await
【发布时间】:2020-01-29 04:22:47
【问题描述】:

我正在创建一个简单的 Java8 并发 CountDownLatch 示例。我正在创建一个大小为 2 的锁存器并启动 2 个线程并在锁存器上调用 await。请参见下面的示例。

package CountDownLatchExample;

import java.util.concurrent.CountDownLatch;

public class CountDownLatchExample {

    static final CountDownLatch latch = new CountDownLatch(2);

    public static void main(String[] args) throws InterruptedException {
        MyThread thread = new MyThread(latch);
        new Thread(thread).start();
        new Thread(thread).start();
        latch.await();
        System.out.println(Thread.currentThread().getName() + " done.");
    }

}

class MyThread implements Runnable {

    CountDownLatch latch;

    MyThread(CountDownLatch latch) {
        this.latch = latch;
    }

    @Override
    public void run() {
        latch.countDown();
        System.out.println(Thread.currentThread().getName() + " completed.");
    }
}

我希望 Thread-0、Thread-1 在 main 完成(基于 sysout)之前完成。但是,当我执行程序时,有时甚至会在 Thread-1 完成之前打印“主要完成”消息。是我的实现还是我的理解不正确?请提出建议。

输出:

> Task :CountDownLatchExample.main()
Thread-0 completed.
main done.
Thread-1 completed.

【问题讨论】:

  • 哎呀。刚刚意识到倒计时会减少闩锁,因此它甚至在打印“线程完成”消息之前就达到了零。

标签: java multithreading concurrency


【解决方案1】:

当我执行时,我得到这个输出:

Thread-0 completed.
Thread-1 completed.
main done.

线程之间的上下文切换也可以在调用latch.countDown()之后发生;在运行方法中。 我建议您修改以下运行方法以获得所需且一致的结果。

 @Override
    public void run() {
        System.out.println(Thread.currentThread().getName() + " completed.");
        latch.countDown();

    }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-02-26
    • 1970-01-01
    • 2017-07-19
    • 1970-01-01
    • 2015-07-04
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多