• C# 多线程使用信号量控制处理效率,统计活动中的线程


    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Threading;
    using System.Threading.Tasks;
     
    namespace ConsoleApp1
    {
        class Program
        {
            //信号量Semaphore限制可同时访问某一资源或资源池的线程数。指示控制的资源初始和最大线程并发数为2
            static Semaphore sema = new Semaphore(1, 1);
            static int aliveCount = 0;
            static object obj = new object();
     
            static void Main(string[] args)
            {
                for (int i = 0; i < 10; i++)
                {
                    var thread = new Thread(Test) { Name = $"Thread{i}" };
                    thread.Start();
                }
                var timer = new System.Timers.Timer();
                timer.Interval = 1000;
                timer.Elapsed += MTMShareCountry;
                timer.Enabled = true;
                timer.AutoReset = true;
                timer.Start();
                Console.ReadKey();
            }
     
            private static void MTMShareCountry(object sender, System.Timers.ElapsedEventArgs e)
            {
                Console.WriteLine($"现在alive线程数: {aliveCount}");
            }
     
     
            static void Test()
            {
                lock (obj)
                {
                    aliveCount++;
                }
                string threadName = Thread.CurrentThread.Name;
                Console.WriteLine($"{threadName} 正在等待一个许可证.......");
                //申请一个许可证
                sema.WaitOne();
     
                Console.WriteLine($"............... {threadName} 申请到许可证................");
                for (int k = 0; k < 3; k++)
                {
                    Console.WriteLine($"ThreadName:{threadName} 循环:{k}");
                    Thread.Sleep(1000);
                }
                sema.Release();   //释放一个许可证
                lock (obj)
                {
                    aliveCount--;
                }
            }
        }
    }

  • 相关阅读:
    LeetCode No961. 在长度 2N 的数组中找出重复 N 次的元素
    LeetCode No468. 验证IP地址
    LeetCode No56. 合并区间
    LeetCode No50. Pow(x, n)
    LeetCode No1021. 删除最外层的括号
    LeetCode No53. 最大子数组和
    LeetCode No52. N皇后 II
    LeetCode No57. 插入区间
    LeetCode No965. 单值二叉树
    LeetCode No48. 旋转图像
  • 原文地址:https://www.cnblogs.com/smartsmile/p/14415924.html
Copyright © 2020-2023  润新知