【发布时间】:2018-08-19 09:44:11
【问题描述】:
我正在尝试了解线程。所以我在一本官方书籍中看到了这篇文章:
public static class Program
{
public static void ThreadMethod()
{
for (int i = 0; i < 10; i++)
{
Console.WriteLine("Thread Step: {0}", i); // A - see comment!!
Thread.Sleep(0); // B
}
}
public static void Main()
{
Thread t = new Thread(new ThreadStart(ThreadMethod));
t.Start();
for (int i = 0; i < 4; i++)
{
Console.WriteLine("This is supposedly the main thread.");
Thread.Sleep(0);
}
t.Join();
Console.ReadLine();
}
}
现在,书中说预期的行为应该是这样的(暗示输出是可预测的,因为如果您知道规则以及如何配置线程,线程是可预测的):
// Displays
//This is supposedly the main thread.
//Thread step: 0
//This is supposedly the main thread.
//Thread step: 1
//This is supposedly the main thread.
//Thread step: 2
//This is supposedly the main thread.
//Thread step: 3
//Thread step: 4
//Thread step: 5
//Thread step: 6
//Thread step: 7
//Thread step: 8
//Thread step: 9
//Thread step: 10
但是,每次运行控制台应用程序的实际结果都不同,为什么? 其次,我希望首先在屏幕上看到“Thread Step:0”,因为 A)第一个线程将其输出到控制台,并且仅在此之后 B)运行 Thread.Sleep(0),这意味着当前线程被放置休眠以等待另一个同等优先级的线程来接管(如果可用)。
This is supposedly the main thread.
This is supposedly the main thread.
Thread Step: 0
This is supposedly the main thread.
Thread Step: 1
This is supposedly the main thread.
Thread Step: 2
Thread Step: 3
Thread Step: 4
Thread Step: 5
Thread Step: 6
Thread Step: 7
Thread Step: 8
Thread Step: 9
再次运行,得到另一个结果:
This is supposedly the main thread.
This is supposedly the main thread.
Thread Step: 0
Thread Step: 1
Thread Step: 2
Thread Step: 3
Thread Step: 4
Thread Step: 5
Thread Step: 6
Thread Step: 7
Thread Step: 8
Thread Step: 9
This is supposedly the main thread.
This is supposedly the main thread.
还有一个:
This is supposedly the main thread.
Thread step: 0
This is supposedly the main thread.
Thread step: 1
Thread step: 2
Thread step: 3
Thread step: 4
Thread step: 5
Thread step: 6
Thread step: 7
Thread step: 8
Thread step: 9
This is supposedly the main thread.
This is supposedly the main thread.
还有一个:
This is supposedly the main thread.
Thread step: 0
This is supposedly the main thread.
Thread step: 1
This is supposedly the main thread.
Thread step: 2
This is supposedly the main thread.
Thread step: 3
Thread step: 4
Thread step: 5
Thread step: 6
Thread step: 7
Thread step: 8
Thread step: 9
还有一个:
Thread step: 0
Thread step: 1
This is supposedly the main thread.
Thread step: 2
This is supposedly the main thread.
This is supposedly the main thread.
This is supposedly the main thread.
Thread step: 3
Thread step: 4
Thread step: 5
Thread step: 6
Thread step: 7
Thread step: 8
Thread step: 9
【问题讨论】:
-
bolov,你在书中的摘录/代码片段中看到了很多次,在摘录的下面是输出。没有免责声明,在这种情况下,输出实际上是可能的输出之一。它之前提到可以对线程进行优先级排序,但未能将这个想法与他们给出的示例联系起来。
标签: c# multithreading thread-sleep