我循环遍历我的线程数组并启动每个线程。然后在第二个循环中,我为每个线程调用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() 时看到的。Beforedata.array[0] = 0data.array[1] = 1Creating Thread_0 with threadInt 0Starting Thread_0Creating Thread_1 with threadInt 1Starting Thread_1Running Thread_0Thread: Thread_0 adding 5 to threadInt Afterdata.array[0] = 5Thread Thread_0 exiting.Running Thread_1data.array[1] = 1Thread: Thread_1 adding 5 to threadInt Thread Thread_1 exiting.这就是我期望使用 thread.join 看到的,以及当我使用 Count Down Latch 时所看到的。Beforedata.array[0] = 0data.array[1] = 1Creating Thread_0 with threadInt 0Starting Thread_0Creating Thread_1 with threadInt 1Starting Thread_1Running Thread_0Thread: Thread_0 adding 5 to threadInt Running Thread_1Thread: Thread_1 adding 5 to threadInt Thread Thread_0 exiting.AfterThread Thread_1 exiting.data.array[0] = 5data.array[1] = 6
2 回答
三国纷争
TA贡献1804条经验 获得超7个赞
正如Solomon Slow指出的那样,错误是我正在创建一个新线程,然后忘记了它。该错误是在尝试解决不相关的问题时引入的。下面的代码为我提供了与倒计时闩锁相同的结果(预期)。
for (UserThread thread : threadArray)
{
thread = new UserThread();
thread.start();
}
for (UserThread thread : threadArray)
{
if (thread != null)
thread.join();
}
HUX布斯
TA贡献1876条经验 获得超6个赞
据了解,此处的问题与线程变量引用分配有关。您正在尝试分配给变量 ,它是迭代变量。此赋值不会更改数组,因为变量是对当前数组元素的引用副本。如果你想正确初始化,你应该在与计数器的公共循环中执行此操作:threadthread
for (int i = 0; i < threadArray.length; ++i) {
UserThread newThread = new UserThread();
threadArray[i] = newThread;
threadArray[i].start();
}
之后,您似乎可以加入线程。
添加回答
举报
0/150
提交
取消