多线程10-SemaphoreSlim
Posted shidengyun
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了多线程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();
}
}
以上是关于多线程10-SemaphoreSlim的主要内容,如果未能解决你的问题,请参考以下文章