java - 当我在 CyclicBarrier 回调中调用 join 时,应用程序挂起

标签 java multithreading concurrency cyclicbarrier

我在启动线程时有以下方法测试:

public static void main(String[] args) throws InterruptedException {
        List<Thread> threads = new ArrayList<>();
        final CyclicBarrier cyclicBarrier = new CyclicBarrier(1);
        Thread thread = new Thread(new CallbackThread(cyclicBarrier, threads));
        threads.add(thread);
        thread.start();          
    }

回调线程如下所示:

class CallbackThread implements Runnable {
    CyclicBarrier cyclicBarrier;
    List<Thread> threads;

    CallbackThread(CyclicBarrier cyclicBarrier, List<Thread> threads) {
        this.cyclicBarrier = cyclicBarrier;
        this.threads = threads;
    }

    @Override
    public void run() {
        try {
            cyclicBarrier.await();
        } catch (InterruptedException e) {
            e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
        } catch (BrokenBarrierException e) {
            e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
        }
        System.out.println("Threads started");
        for (Thread thread1 : threads) {
            try {
                thread1.join();
            } catch (InterruptedException e) {
                e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
            }
        }
        System.out.println("Threads finished");

    }
}

当我运行应用程序时,我看到以下输出:

Threads started

并且应用程序挂起。

我不明白为什么。

如果将连接逻辑替换为主方法 - 一切都很好。

public static void main(String[] args) throws InterruptedException {
        List<Thread> threads = new ArrayList<>();
        final CyclicBarrier cyclicBarrier = new CyclicBarrier(1);
        Thread thread = new Thread(new CallbackThread(cyclicBarrier, threads));
        threads.add(thread);
        thread.start();
        for (Thread thread1 : threads) {
            try {
                thread1.join();
            } catch (InterruptedException e) {
                e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
            }
        }
        System.out.println("Threads finished");

    }

你能解释一下这种差异吗?
恕我直言,它应该工作相同。

最佳答案

第一个示例中的代码在其自己的线程上调用 join。您将其添加到列表中,线程会迭代列表并连接列表中的每个线程。

关于java - 当我在 CyclicBarrier 回调中调用 join 时,应用程序挂起,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31913718/

相关文章:

java - 通过 Web 套接字的应用程序到应用程序通信

java - Spring注解的区别

java - 创建n个变量java

java - Nifi ExecuteScript 与 Groovy : OOM exception

java - 如何在 ibatis sqlMap 配置中使用文件资源而不是类路径资源?

java - 为什么下面的代码中 FirstThread 总是先于 SecondThread 运行?

c++ - 如何中断 libfcgi 中的 Accept 方法?

Java多线程,奇怪的东西

java - Flow API 中的 subscription.request(n) 如何在任意 n 值执行背压?

c# - 仅当满足条件时才从 ConcurrentQueue 中出队