我运行了以下代码块,在main方法下的for循环中会初始化6个线程,从thread1依次至thread6,但在命令行中显示线程生成顺序与for循环运行的顺序不一致
代码块:
using System;
using System.Threading;
using static System.Console;
using static System.Threading.Thread;
namespace Chapter2.Recipe3
{
class Program
{
static void Main(string[] args)
{
for (int i = 1; i <= 6; i++)
{
string threadName = "Thread " + i;
int secondsToWait = 2 + 2 * i;
var t = new Thread(() => AccessDatabase(threadName, secondsToWait));
t.Start();
}
}
static SemaphoreSlim _semaphore = new SemaphoreSlim(4);
static void AccessDatabase(string name, int seconds)
{
WriteLine($"{name} waits to access a database");
_semaphore.Wait();
WriteLine($"{name} was granted an access to a database");
Sleep(TimeSpan.FromSeconds(seconds));
WriteLine($"{name} is completed");
_semaphore.Release();
}
}
}
命令行结果:
Thread4 waits to access database
Thread3 waits to access database
Thread1 waits to access database
Thread6 waits to access database
Thread2 waits to access database
Thread5 waits to access database
Thread2 was granted an access to a database
Thread1 was granted an access to a database
Thread4 was granted an access to a database
Thread3 was granted an access to a database
Thread1 is completed
Thread5 was granted an access to a database
Thread2 is completed
Thread6 was granted an access to a database
Thread3 is completed
Thread4 is completed
Thread5 is completed
Thread6 is completed
Press any key to continue...
想请教大家为什么线程生成的顺序与for循环里面定义的顺序不一致,谢谢!