關於Thread.Sleep(0);

關於Thread.Sleep(0);

Thread.Sleep(0)的作用,就是”觸發操作系統立刻重新進行一次CPU競爭”。

競爭的結果也許是當前Thread仍然獲得CPU控制權,也許會換成別的Thread獲得CPU控制權。

所以在Loading大的系統中,可能丟失執行權到CPU下次有空,造成非預期的系統錯誤。

1
2
3
4
5
6
7
8
9
10
private long delayMilliSeconds = 0;
//直接執行Thread.Sleep(0);有可能會發生非預期的錯誤,這邊要多加一層判斷,當delayMilliSeconds > 0
//才能執行Thread.Sleep(delayMilliSeconds);方法。
if (delayMilliSeconds > 0) {
try {
TimeUnit.MILLISECONDS.sleep(delayMilliSeconds);
} catch (InterruptedException e) {
LogUtils.error.error(e.getMessage(), e);
}
}