0

我在启动线程的地方进行了以下方法测试:

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();          
    }

CallBack 线程如下所示:

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

和应用程序挂起。

我不明白为什么。

如果将连接逻辑替换为 main 方法 - 所有商品都很好。

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");

    }

你能解释一下这个区别吗?
恕我直言,它应该工作相同。

4

2 回答 2

2

第一个示例中的代码在其自己的线程上调用 join。您将它添加到列表中,线程遍历列表并加入列表中的每个线程。

于 2015-08-10T07:23:30.757 回答
1

您正在加入self。这就是为什么程序永远不会结束的原因。

当您join()从主线程调用时,主线程正在尝试加入它创建的线程,即CallableThread. 所以是对的。

但是当你加入时CallableThread,你正在传递threads[]包含对自身的引用。所以它正在加入自己,这不会结束。

于 2015-08-10T07:24:05.980 回答