我循環遍歷我的線程數組并啟動每個線程。然后在第二個循環中,我為每個線程調用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
提交
取消