为什么Java的Thread.join()不等待所有线程在此代码中死亡?

时间:2019-03-28 16:32:54

标签: java multithreading

我遍历线程数组并开始每个线程。然后在第二个循环中,我为每个线程调用thread.join(),希望它等待所有线程死亡,然后主线程恢复执行,但这不会发生。线程似乎没有联接,但在联接之后继续执行。

我尝试过为每个线程分别调用join方法,但这是行不通的。我使用Count Down Latch找到了解决方法,它给了我想要和期望的结果,但是我希望使用内置的线程方法。

for (UserThread thread : threadArray)
{
    UserThread newThread = new UserThread();
    thread = newThread;
    thread.start();
}
for (UserThread thread : threadArray)
{
    thread.join();
}

这是我使用thread.join()时看到的。

Before
data.array[0] = 0
data.array[1] = 1

Creating Thread_0 with threadInt 0
Starting Thread_0
Creating Thread_1 with threadInt 1
Starting Thread_1
Running Thread_0

Thread: Thread_0 adding 5 to threadInt 
After
data.array[0] = 5
Thread Thread_0 exiting.
Running Thread_1
data.array[1] = 1
Thread: Thread_1 adding 5 to threadInt 
Thread Thread_1 exiting.

这是我希望使用thread.join看到的内容,以及使用Count Down Latch时看到的内容。

Before
data.array[0] = 0
data.array[1] = 1

Creating Thread_0 with threadInt 0
Starting Thread_0
Creating Thread_1 with threadInt 1
Starting Thread_1
Running Thread_0
Thread: Thread_0 adding 5 to threadInt 
Running Thread_1
Thread: Thread_1 adding 5 to threadInt 
Thread Thread_0 exiting.

After
Thread Thread_1 exiting.
data.array[0] = 5
data.array[1] = 6

2 个答案:

答案 0 :(得分:0)

据这里可以看到的问题与线程变量引用分配有关。 您正在尝试分配给变量thread,它是迭代变量。该分配不会更改数组,因为thread变量是对当前数组元素的引用的副本。如果要正确初始化,则应使用counter在公共循环中完成该操作:

for (int i = 0; i < threadArray.length; ++i) {
    UserThread newThread = new UserThread();
    threadArray[i] = newThread;
    threadArray[i].start();
}

看来您以后可以加入线程了。

答案 1 :(得分:0)

该错误是所罗门·斯洛(Solomon Slow)指出的,我正在创建一个新线程,然后忘记了它。尝试解决一个不相关的问题时,就引入了该错误。下面的代码为我提供了与Count Down Latch相同的结果(预期)。

    for (UserThread thread : threadArray)
    {
        thread = new UserThread();
        thread.start();
    }

    for (UserThread thread : threadArray)
    {
        if (thread != null)
            thread.join();
    }