C#线程同步SemaphoreSlim类介绍
SemaphoreSlim类限制了同时访问一个资源的线程数量
代码如下:
1 static SemaphoreSlim semaphoreSlim = new SemaphoreSlim(4); 2 3 static void AccessDatabase(string name, int seconds) 4 { 5 Console.WriteLine($"{name}等待访问数据库"); 6 semaphoreSlim.Wait(); 7 Console.WriteLine($"{name}被授权访问数据库"); 8 Thread.Sleep(TimeSpan.FromSeconds(seconds)); 9 Console.WriteLine($"{name}访问数据库已经完成"); 10 semaphoreSlim.Release(); 11 } 12 13 static void Main(string[] args) 14 { 15 for (int i = 1; i <= 6; i++) 16 { 17 string threadName = $"线程{i}"; 18 int secondsToWait = 2 + 2 * i; 19 var t = new Thread(() => AccessDatabase(threadName, secondsToWait)); 20 t.Start(); 21 } 22 Console.ReadLine(); 23 }
运行结果: