C#多線程的用法4-線程間的協作lock捷徑

來源:互聯網
上載者:User

標籤:console   art   monitor   用法   write   logs   使用   不能   狀態   

線程間協作還可通過lock(加鎖)方式進行,lock屬於C#的Monitor文法糖(Monitor後續講解)。使用簡單快捷,如下:

/// <summary>        /// 多線程協作-lock捷徑        /// 成功解決多線程對單一資源的共用        /// </summary>        private static void MultiThreadSynergicWithLock()        {            int[] array = new int[3];            Thread producer = new Thread(() =>            {                int count = 0;                Random random = new Random();                while (true)                {                    if (10 == count)                        break;                    lock (array)                    {                        array[0] = random.Next(10);                        array[1] = random.Next(10);                        array[2] = random.Next(10);                        count++;                        Console.WriteLine(String.Format("{0} work count:{1}。{2}-{3}-{4}", Thread.CurrentThread.Name, count, array[0], array[1], array[2]));                    }                    Thread.Sleep(100);                }            })            {                Name = "producer"            };            Thread customer = new Thread(() =>            {                //Console.WriteLine(String.Format("{0} start work", Thread.CurrentThread.Name));                int count = 0;                while (true)                {                    if (10 == count)                        break;                    lock (array)                    {                        count++;                        Console.WriteLine(String.Format("{0} work count:{1}。{2}-{3}-{4}", Thread.CurrentThread.Name, count, array[0], array[1], array[2]));                        array[0] = 0;                        array[1] = 0;                        array[2] = 0;                    }                    Thread.Sleep(10);                }            })            {                Name = "customer"            };            producer.Start();            customer.Start();        }

說明:

1、通過lock成功解決了多個線程對同一資源的共用使用問題,確保一個線程在lock到資源後,另外需要資源的線程只能處於等待狀態。

2、lock並不能解決線程間順序執行的問題(線程順序執行是指:要求線程A,B滿足,A先執行,B再執行,A又執行,B再次執行這種交替模式)

C#多線程的用法4-線程間的協作lock捷徑

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.