麦田

不积跬步无以至千里.

  博客园 :: 首页 :: 博问 :: 闪存 :: 新随笔 :: 联系 :: 订阅 订阅 :: 管理 ::
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace DemoTest
{
    class Program
    {
        static SemaphoreSlim semaphore = new SemaphoreSlim(1); // 限制同时访问资源的线程数量为2

        static void Main()
        {
            for (int i = 1; i <= 5; i++)
            {
                int threadId = i;
                Task.Run(() => AccessResource(threadId));
            }

            Console.ReadLine();
        }

        static void AccessResource(int threadId)
        {
            Console.WriteLine("线程 {0} 正在等待资源.", threadId);

            semaphore.Wait();

            Console.WriteLine("线程 {0} 开始访问资源.------", threadId);
            Thread.Sleep(2000); // 模拟访问资源的耗时操作
            Console.WriteLine("线程 {0} 结束访问资源.------", threadId);

            semaphore.Release();
            Console.WriteLine("线程 {0} 释放资源.", threadId);
        }
    }
}

 

posted on 2025-03-31 11:43  一些记录  阅读(20)  评论(0)    收藏  举报