多线程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();
        }
    }
posted @ 2016-06-20 19:46  shidengyun  阅读(281)  评论(0编辑  收藏  举报