我目前正在阅读这篇优秀的文章,其中有如下文字:
Thread.Sleep(0)立即放弃线程当前的时间片,自愿地将CPU交出给其他线程。
我想测试一下这个方法,以下是我的测试代码:
static string s = "";
static void Main(string[] args)
{
//Create two threads that append string s
Thread threadPoints = new Thread(SetPoints);
Thread threadNewLines = new Thread(SetNewLines);
//Start threads
threadPoints.Start();
threadNewLines.Start();
//Wait one second for threads to manipulate string s
Thread.Sleep(1000);
//Threads have an infinite loop so we have to close them forcefully.
threadPoints.Abort();
threadNewLines.Abort();
//Print string s and wait for user-input
Console.WriteLine(s);
Console.ReadKey();
}
threadPoints和threadNewLines函数的作用:
static void SetPoints()
{
while(true)
{
s += ".";
}
}
static void SetNewLines()
{
while(true)
{
s += "\n";
Thread.Sleep(0);
}
}
如果我正确理解Thread.Sleep(0),输出应该类似于这样:
............ |
.............. |
................ | <- End of console
.......... |
............. |
............... |
但我得到的输出是:
....................|
....................|
.... |
|
|
....................|
....................|
................. |
|
考虑到文章一开始提到的被许多程序员高度推荐,我只能假设我对Thread.Sleep(0)的理解是错误的。因此,如果有人能澄清一下,我将非常感激。
Thread.Sleep(0)
时,可能会有另一个线程写入屏幕,也可能不会。 - Jodrell