C#之:线程同步 Semaphore类和 SemaphoreSlim类

记一次SemaphoreSlim的使用

 1 using System;
 2 using System.Threading;
 3 
 4 namespace ConsoleApp1
 5 {
 6     public class Program2
 7     {
 8         #region Field(字段)
 9 
10         private static SemaphoreSlim _semaphore = new SemaphoreSlim(4);
11 
12         #endregion Field(字段)
13 
14         #region Public Method(公开方法)
15 
16         private static void acquireSemaphore(string name, int seconds)
17         {
18             Console.WriteLine("{0} wait " + DateTime.Now, name);
19             _semaphore.Wait();
20             Console.WriteLine("{0} access " + DateTime.Now, name);
21             Thread.Sleep(TimeSpan.FromSeconds(seconds));
22             Console.WriteLine("{0} Release " + DateTime.Now, name);
23             _semaphore.Release();
24         }
25 
26         private static void Main(string[] args)
27         {
28             for (int i = 1; i <= 6; i++)
29             {
30                 string threadName = "thread" + i;
31                 int secondsToWait = 2 + 2 * i;
32                 var t = new Thread(() => acquireSemaphore(threadName, secondsToWait));
33                 t.Start();
34             }
35             Console.ReadKey();
36         }
37 
38         #endregion Public Method(公开方法)
39     }
40 }

执行结果如下:

解释下:

SemaphoreSlim(4)限定最大入口并发数4,前面‘thread1’,‘thread2’,‘thread3’,‘thread5’四个线程先到,‘thread4’、‘thread6’后到进行等待,4秒后thread1释放,'thread6'进入,6秒后thread2释放,thread4进入。
posted @ 2020-04-24 17:38  Nine4酷  阅读(298)  评论(0编辑  收藏  举报