码迷,mamicode.com
首页 > 其他好文 > 详细

同步锁

时间:2015-06-26 14:54:08      阅读:119      评论:0      收藏:0      [点我收藏+]

标签:

 class Program
    {
        static void Main(string[] args)
        {
            //控制台默认输出行数是300,可以设置
            Console.BufferHeight = 1000;

            TicketSeller t1 = new TicketSeller("A");
            TicketSeller t2 = new TicketSeller("B");
           
            Console.ReadLine();
        }

    }


    public class TicketSeller
    {
        public static int count = 500;
        public static object locker = new object();

        public TicketSeller(string name)
        {
            Console.WriteLine(count);
            Thread th = new Thread(Sell);
            th.Name = name;
            th.IsBackground = true;
            th.Start();
            Console.WriteLine(count);
        }

        public void Sell()
        {

            while (count > 0)
            {
                //引用类型对象在内存中分配的对象头空间(栈空间)最后2bit存放锁标识
                lock (locker)
                {
                    TicketSeller.count--;
                    Console.WriteLine(System.Threading.Thread.CurrentThread.Name + "剩余{0}", count);
                }

            }
        }
    }

 

同步锁

标签:

原文地址:http://www.cnblogs.com/tgdjw/p/4602076.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!