我是C#的新手,仍在学习线程概念。我写了一个程序,它是如下C语言中的线程概念#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Threading;
namespace ConsoleApplication17
{
class Program
{
static void Main(string[] args)
{
System.Threading.ThreadStart th1 = new System.Threading.ThreadStart(prnt);
Thread th = new Thread(th1);
th.Start();
bool t = th.IsAlive;
for (int i = 0; i < 10; i++)
{
Console.WriteLine(i + "A");
}
}
private static void prnt()
{
for (int i = 0; i < 10; i ++)
{
Console.WriteLine(i + "B");
}
}
}
}
我期待的输出,如: -
1A
2A
1B
3A
2B...
,因为我相信,这两个主线程和新创建的线程应该同时执行。
但是输出是有序的,首先调用prnt
函数,然后执行循环的Main
方法。
你的代码看起来罚款;大概它只是需要更长的时间才能完成主线程。为每个'for for循环添加'Thread.Sleep(500);';这将有助于确保他们花费更长时间运行,以便您可以看到发生了什么。 – JohnLBevan
线程调度是不可预测的,许多程序都会失败(比赛条件),因为程序员假定线程不存在某些理想行为,例如假设线程始终并行运行并处于完美同步状态。他们不。考虑您的程序如何在带有大型(100ms +)时间片的操作系统的单线程处理器上运行。 – Dai