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);
}
}
}