天天看點

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--;
            }
        }
    }
}
           
C# 多線程使用信号量控制處理效率,統計活動中的線程

繼續閱讀