我有一些代碼,如下所示:效率 - 循環使用Thread.yield的是等待變量的變化
while (this.conditionIsNotYetMet){
if (timeout()) break;
// Don't do anything, just wait till the condition is
// filled by a different thread or timeout occurs.
}
performSomeCode(); // this code relies on the condition having been met
代碼工作 - 最終另一個線程充滿狀態,而代碼執行。
我很好奇是否會拋出一個Thread.yield() - 這種方式似乎是正確的,在這個階段,我感覺不到性能差異 - 但我擔心未來它可能會有所作爲,例如在不同的平臺上。
即代碼將成爲
while (this.conditionIsNotYetMet){
if (timeout()) break;
Thread.yield(); // <---- CHANGE IS HERE!!!!
// Don't do anything, just wait till the condition is
// filled by a different thread or timeout occurs.
}
performSomeCode(); // this code relies on the condition having been met
我知道,可能有一個更正式的方式來實現使用鎖或AsynchronousTasks這種模式,但這種方法效果很好的時刻,是非常明顯的,所以爲什麼改變?
你可以實現'wait-notify'模式 – 2013-04-25 06:14:10
'timeout()'做什麼? – SimonC 2013-04-25 06:14:31
我在這裏使用timeout()來表示任何類型的超時條件以確保活躍性。在我的情況下,它檢查System.currentTimeMillis()對於在while循環之前進行的測量 – Alex 2013-04-25 07:17:40