一个多线程的小例子---C#高级编程学习

来源:互联网 发布:网络阅卷y100edu 编辑:程序博客网 时间:2024/05/22 07:40

C#高级编程学习时的小例子:

public  void main()        {            int threadCount = 6;            int semaphoreCount = 3;            var semaphore = new SemaphoreSlim(semaphoreCount,                semaphoreCount);            var threads = new Thread[threadCount];            for (int i = 0; i < threadCount; i++)            {                threads[i] = new Thread(threadMain);                threads[i].Start(semaphore);             }            for (int i = 0; i < threadCount; i++)            {                threads[i].Join();             }            Console.WriteLine("All threads Finished");         }        public void threadMain(object o)        {            SemaphoreSlim semaphore = o as SemaphoreSlim;            Trace.Assert(semaphore != null, "o must be a Semaphore type");            bool isCompleted = false;            while(!isCompleted)            {                if (semaphore.Wait(600))                {                    try                    {                        Console.WriteLine("Thread {0} locks the semaphore",                            Thread.CurrentThread.ManagedThreadId);                        Thread.Sleep(2000);                    }                    finally                    {                        semaphore.Release();                        Console.WriteLine("Thread {0} releases the semaphore",                            Thread.CurrentThread.ManagedThreadId);                        isCompleted = true;                    }                }                else                 {                    Console.WriteLine("TimeOut for Thread {0};Wait again",                        Thread.CurrentThread.ManagedThreadId);                 }                        }                }

结果:





原创粉丝点击