【发布时间】:2022-01-10 23:10:12
【问题描述】:
有如下代码,问题是: 哪些玩家会先被写入终端
我很容易理解 Start() 和 Join() 的功能,即立即启动线程。但是,我不确定首先将哪些玩家写入终端。我的理解是,可能是threadE、threadC、threadA,没找到正确答案。
如果有人有线索?谢谢。
class Player
{
private readonly string tag;
public Player(string name)
{
this.tag = name;
}
public void Run()
{
Thread.Sleep(100);
Console.Write(tag + ",");
}
static void Main(string[] args)
{
Thread threadA = new Thread(new Player("A").Run);
Thread threadB = new Thread(new Player("B").Run);
Thread threadC = new Thread(new Player("C").Run);
Thread threadD = new Thread(new Player("D").Run);
Thread threadE = new Thread(new Player("E").Run);
threadE.Start();
threadC.Start();
threadA.Start();
threadC.Join();
threadB.Start();
threadA.Join();
threadD.Start();
threadB.Join();
threadD.Join();
threadE.Join();
}
}
【问题讨论】:
-
所有可以肯定的说法是 B 肯定发生在 C 之后,而 D 肯定发生在 C 和 A 之后。其他一切都是实现定义的,并且可能会在每次运行时发生变化,具体取决于调度器正在做
-
这是一场竞赛,你不能假设一个线程在没有同步的情况下在另一个线程之前完成。唯一的保证是 C 出现在 B 之前,D 出现在 A 之前,这要归功于 Join() 调用,仅此而已。
-
任何时候你需要一个程序以特定的顺序执行某些事情,这表明这些事情可能都应该在同一个线程中完成。使用多线程的全部目的是让事情发生concurrently。但是,就其定义而言,并发性与事物以明确的、可预测的顺序发生的想法是不相容的。
标签: c# multithreading join sleep