一個多線程的小例子---C#高級編程學習

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

結果:





發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章