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();
        }
    }
}

 

相关文章:

  • 2022-01-18
  • 2021-08-28
  • 2021-09-14
  • 2022-01-15
  • 2022-12-23
  • 2021-06-08
  • 2021-11-02
  • 2021-06-02
猜你喜欢
  • 2022-12-23
  • 2021-07-26
  • 2021-10-14
  • 2021-06-15
  • 2022-02-16
  • 2021-11-01
  • 2021-09-17
相关资源
相似解决方案