标签:
题目:模拟窗口卖票,四个窗口同时对外开放售票,需要按顺序售出。
要求:输出每一张票的售出时间和售出窗口,不能出现票未售出或者被售出多次的情况。
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Threading; using System.IO; using System.Reflection; using System.Diagnostics; namespace SellTicketsSynchronously { class Program { //入口 static void Main(string[] args) { Ticket tc = new Ticket(10); Thread sellWindowA = new Thread(new ParameterizedThreadStart(SellTicket)); Thread sellWindowB = new Thread(new ParameterizedThreadStart(SellTicket)); Thread sellWindowC = new Thread(new ParameterizedThreadStart(SellTicket)); Thread sellWindowD = new Thread(new ParameterizedThreadStart(SellTicket)); sellWindowA.Name = "Window A"; sellWindowB.Name = "Window B"; sellWindowC.Name = "Window C"; sellWindowD.Name = "Window D"; sellWindowA.Start(tc); sellWindowB.Start(tc); sellWindowC.Start(tc); sellWindowD.Start(tc); sellWindowA.Join(); sellWindowB.Join(); sellWindowC.Join(); sellWindowD.Join(); Console.WriteLine("Tickets has been sold out. Press any key to quit:"); Console.ReadLine(); } //卖票方法 public static void SellTicket(object obj) { Ticket ticket = obj as Ticket; while (ticket.NumOfTickets>0) { lock (ticket) { if (ticket.NumOfTickets > 0) { try { ticket.NumOfTickets--; Console.WriteLine( DateTime.Now.ToString()+":"+Thread.CurrentThread.Name + " sells a ticket, " + ticket.NumOfTickets + " tickets left."); } catch (Exception ex) { WriteLog(ex); } } } Random random = new Random(); Thread.Sleep(random.Next(100,500)); } } //打log方法 private static void WriteLog(Exception ex) { string logUrl = Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory) + "\\SellTicketslog.txt"; if (File.Exists(@logUrl)) { using (FileStream fs = new FileStream(logUrl, FileMode.Append)) { using (StreamWriter sw = new StreamWriter(fs, Encoding.Default)) { try { sw.Write(ex); } catch (Exception ex1) { WriteLog(ex1); } finally { sw.Close(); fs.Close(); } } } } else { using (FileStream fs = new FileStream(logUrl, FileMode.CreateNew)) { using (StreamWriter sw = new StreamWriter(fs, Encoding.Default)) { try { sw.Write(ex); } catch (Exception ex1) { WriteLog(ex1); } finally { sw.Close(); fs.Close(); } } } } } } //票类 class Ticket { public int NumOfTickets { get; set; } public Ticket(int num) { this.NumOfTickets = num; } } }
运行结果:
不知道这么写会不会有问题,求指点。
标签:
原文地址:http://www.cnblogs.com/LanTianYou/p/4578776.html