Title: Simulation Window selling tickets, four Windows at the same time to open the ticket sales, need to be sold sequentially.
Requirements: The output of each ticket and the sale of the window, cannot appear the ticket has not been sold or sold more than one time.
usingSystem;usingSystem.Collections.Generic;usingSystem.Linq;usingSystem.Text;usingSystem.Threading.Tasks;usingSystem.Threading;usingSystem.IO;usingSystem.Reflection;usingSystem.Diagnostics;namespacesellticketssynchronously{classProgram {//entrance Static voidMain (string[] args) {Ticket TC=NewTicket (Ten); Thread Sellwindowa=NewThread (NewParameterizedthreadstart (Sellticket)); Thread SELLWINDOWB=NewThread (NewParameterizedthreadstart (Sellticket)); Thread SELLWINDOWC=NewThread (NewParameterizedthreadstart (Sellticket)); Thread Sellwindowd=NewThread (NewParameterizedthreadstart (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 have been sold out. Press any key to quit:"); Console.ReadLine (); } //How to sell tickets Public Static voidSellticket (Objectobj) {Ticket Ticket= obj asTicket; 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=NewRandom (); Thread.Sleep (random. Next ( -, -)); } } //hit Log Method Private Static voidWritelog (Exception ex) {stringLogURL = Environment.getfolderpath (Environment.SpecialFolder.DesktopDirectory) +"\\SellTicketslog.txt"; if(File.exists (@logUrl)) {using(FileStream fs =NewFileStream (LogURL, Filemode.append)) { using(StreamWriter SW =NewStreamWriter (FS, Encoding.default)) { Try{SW. Write (ex); } Catch(Exception ex1) {writelog (EX1); } finally{SW. Close (); Fs. Close (); } } } } Else { using(FileStream fs =NewFileStream (LogURL, FileMode.CreateNew)) { using(StreamWriter SW =NewStreamWriter (FS, Encoding.default)) { Try{SW. Write (ex); } Catch(Exception ex1) {writelog (EX1); } finally{SW. Close (); Fs. Close (); } } } } } } //Ticket category classTicket { Public intnumoftickets {Get;Set; } PublicTicket (intnum) { This. Numoftickets =num; } }}
Operation Result:
I do not know whether this will be a problem, ask for advice.
A practice on thread synchronization in C #--simulating multi-window ticketing