C#多线程的用法4-线程间的协作lock快捷方式

线程间协作还可通过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再次执行这种交替模式)

posted @ 2017-08-20 07:45  DW039  阅读(434)  评论(0编辑  收藏  举报