多线程10-SemaphoreSlim
class Program
{
static SemaphoreSlim semaphoreSlim = new SemaphoreSlim(2);
static void Main()
{
for(int i=0;i<=6;i++)
{
string threadName = "Thread" + i;
int secondsToWait = 2 + 2 * i;
var t = new Thread(() => ShowMessage(threadName, secondsToWait));
t.Start();
}
}
static void ShowMessage(string name,int second)
{
Console.WriteLine("{0} watis to showmessage", name);
semaphoreSlim.Wait();
Console.WriteLine("{0} was showmessage", name);
Thread.Sleep(TimeSpan.FromSeconds(5));
Console.WriteLine("{0} is completed", name);
semaphoreSlim.Release();
}
}
{
static SemaphoreSlim semaphoreSlim = new SemaphoreSlim(2);
static void Main()
{
for(int i=0;i<=6;i++)
{
string threadName = "Thread" + i;
int secondsToWait = 2 + 2 * i;
var t = new Thread(() => ShowMessage(threadName, secondsToWait));
t.Start();
}
}
static void ShowMessage(string name,int second)
{
Console.WriteLine("{0} watis to showmessage", name);
semaphoreSlim.Wait();
Console.WriteLine("{0} was showmessage", name);
Thread.Sleep(TimeSpan.FromSeconds(5));
Console.WriteLine("{0} is completed", name);
semaphoreSlim.Release();
}
}