C#线程的同步:锁、死锁

lock实现代码块只允许被一个线程访问

例如多个窗口售票,余票数的计算

using System;
using System.Threading;

namespace ConsoleApplication3
{
    class Program
    {
        int num = 10;
        void SellTicket()//售票
        {
            while (true)
            {
                lock (this)//同一时间,只允许一个线程执行此代码块
                {
                    if (num > 0)
                    {
                        Thread.Sleep(100);
                        Console.WriteLine(Thread.CurrentThread.Name + "剩余票数:" + num);
                        num -= 1;
                    }
                }               
            }
        }
        static void Main(string[] args)
        {
            Program p = new Program();//类的对象,方便引用静态成员
            Thread t1 = new Thread(p.SellTicket);
            t1.Name="窗口1";
            Thread t2 = new Thread(p.SellTicket);
            t2.Name = "窗口2";
            Thread t3 = new Thread(p.SellTicket);
            t3.Name = "窗口3";
            t1.Start();
            t2.Start();
            t3.Start();
        }
    }
}

 

posted @ 2019-05-08 21:03  夕西行  阅读(224)  评论(0编辑  收藏  举报