zoukankan      html  css  js  c++  java
  • 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进入。
  • 相关阅读:
    Eclipse中输入系统变量和运行参数
    poi大数据导入解决方法
    技术走向管理一些思考(2)-建立管理思维
    C. Diverse Permutation(Codeforces Round #275(div2)
    mysql大数据高并发处理
    UVa 11849
    centos7;windows下安装和使用spice
    HDU-4819-Mosaic(二维线段树)
    Using a Plugin
    CSU1608: Particle Collider(后缀数组)
  • 原文地址:https://www.cnblogs.com/Nine4Cool/p/12768981.html
Copyright © 2011-2022 走看看