我目前正在阅读这篇优秀的文章关于线程并阅读以下文本:
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) 的作用是释放 cpu 来处理其他线程,但这并不意味着另一个线程不能是当前线程。如果您尝试将上下文发送到另一个线程,请尝试使用某种信号。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)