C#多線程使用鎖解決爭搶資源問題

C#多線程使用鎖解決爭搶資源問題

class Program
    {
        static object locker=new Object();
        static int init = 100;
        static void Main(string[] args)
        {
            for (int i = 1; i <= 5; i++)
            {
                ThreadStart ts = new ThreadStart(run);
                Thread th = new Thread(ts);
                th.Start();
            }
            Console.ReadLine();
        }
        static void run()
        {
            lock (locker) { 
                while (init > 0) {
                    init--;
                    Console.WriteLine("線程:"+Thread.CurrentThread.Name+",執行減1後的結果:"+init.ToString());
                    //Thread.Sleep(100);
                }
            }
        }
    }
發佈了47 篇原創文章 · 獲贊 3 · 訪問量 1萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章