我正在创建一个简单的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在主要完成(基于sysout)之前一致地完成。但是,当我执行程序时,有时甚至在Thread-1完成之前都会打印“ main done”消息。我的实现方式还是我的理解不正确?请提出建议。

输出:

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

最佳答案

执行时,我得到以下输出:

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


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

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

    }

08-27 12:32