C# 多线程 简单的同步售票系统代码

来源:互联网 发布:arp scan python 编辑:程序博客网 时间:2024/04/30 04:44
using System;using System.Threading;//进程同步//共50张票,3个窗口售卖namespace Chapter10_Practice{    class TicketRest    {        int ticket = 1;        public void sell()        {            while (ticket <= 50)            {                lock (this)                {                    if (ticket > 50) break; //这里一定要判断。                    Console.WriteLine("窗口{0}售票员:售出第{1}号车票", Thread.CurrentThread.Name, ticket);                    ticket++;                }            }        }    }    class Program    {        static void Main(string[] args)        {            TicketRest a = new TicketRest();            Thread t1 = new Thread(a.sell);            t1.Name = "1";            Thread t2 = new Thread(a.sell);            t2.Name = "2";            Thread t3 = new Thread(a.sell);            t3.Name = "3";            t1.Start();            t2.Start();            t3.Start();            Console.ReadKey();        }    }}
0 0