gpt4 book ai didi

c# - 线程 : Why does this code show 5 in output in thread

转载 作者:太空宇宙 更新时间:2023-11-03 15:07:20 25 4
gpt4 key购买 nike

<分区>

我有一个简单的代码,它有一个锁并创建了 5 个线程。

static readonly object _object = new object();

static void A(int currentValue)
{
lock (_object)
{
Console.WriteLine(currentValue + " Start");
Console.WriteLine(currentValue + " End");
}
}

static void Main(string[] args)
{
for (int i = 0; i < 5; i++)
{
Thread t = new Thread(() => A(i));
t.Name = "Thread " + i;
Console.WriteLine(t.Name + " Created");
t.Start();
}
Console.ReadKey();
}

当我运行此代码时,输​​出中显示以下内容。

Thread 0 Created
Thread 1 Created
1 Start
1 End
Thread 2 Created
2 Start
2 End
Thread 3 Created
3 Start
3 End
Thread 4 Created
4 Start
4 End
5 Start
5 End

当我只创建 5 个线程 (0 - 4) 时。为什么我会看到 5 Start 和 5 End 的条目?

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com