Thread.sleep代码(0)所描述不起作用?

编程入门 行业动态 更新时间:2024-10-06 01:38:17
本文介绍了Thread.sleep代码(0)所描述不起作用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我目前正在读穿线这个优秀的文章并阅读下面的文字:

I am currently reading this excellent article on threading and read the following text:

的Thread.Sleep(0)放弃立即线程的当前时间片,自愿交出CPU给其他线程。

Thread.Sleep(0) relinquishes the thread’s current time slice immediately, voluntarily handing over the CPU to other threads.

我想测试这一点,下面是我的测试代码:

I wanted to test this and below is my test code:

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运行的功能:

The functions that threadPoints and threadNewLines run:

static void SetPoints() { while(true) { s += "."; } } static void SetNewLines() { while(true) { s += "\n"; Thread.Sleep(0); } }

如果我(0)正确认识了Thread.Sleep,输出应该是这样的:

If I understand Thread.Sleep(0) correctly, the output should be something like this:

............ | .............. | ................ | <- End of console .......... | ............. | ............... |

不过,我得到这个作为输出:

But I get this as output:

....................| ....................| .... | | | ....................| ....................| ................. | |

看到作为文章的开头提到的文章深受许多程序员建议,我只能假设我的Thread.Sleep的理解(0)是错误的。所以,如果有人可以澄清一下,我会非常感激。

Seeing as the article mentioned in the beginning of the post is highly recommended by many programmers, I can only assume that my understanding of Thread.Sleep(0) is wrong. So if someone could clarify, I'd be much obliged.

推荐答案

什么的Thread.Sleep(0)是释放CPU的以处理其他的线程,但是这并不意味着另一个线程不能当前之一。如果你想上下文发送到另一个线程,尝试使用某种信号。

What thread.sleep(0) is to free the cpu to handle other threads, but that doesn't mean that another thread couldn't be the current one. If you're trying to send the context to another thread, try to use some sort of signal.

更多推荐

Thread.sleep代码(0)所描述不起作用?

本文发布于:2023-11-12 20:59:24,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1582516.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:不起作用   代码   Thread   sleep

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!