我是 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
方法。
最佳答案
也许 10 个 cicle 不足以看到两个线程同时运行。 使用更长的循环或在循环迭代中放置 Thread.Sleep (100)。 启动线程非常昂贵。可能发生的情况是,由于线程启动需要时间,您的主循环在线程循环开始之前执行
关于c# - C#中的线程概念,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33583245/