我循环遍历我的线程数组并启动每个线程。然后在第二个循环中,我为每个线程调用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
三国纷争
HUX布斯
相关分类