This paper uses Java multithreading to realize the function of simulating the ticket selling of multiple stations.
Keywords: Java multithreaded shared variable implementation runnable interface volatile thread synchronization.
The code is as follows
Ticket class
PackageEx7_ticketsaler;/*multiple threads of the same object THREAD0/1/2, operations on shared variables count, need to declare the value of count as volatile * and because multiple threads operate on the same object ticket, so count is a resource-shared **/ Public classTicketImplementsrunnable{volatile intCount = 1000;//total number of votesBoolean flag =true; Object Locobj=NewObject (); @Override Public voidrun () {//TODO auto-generated Method Stub//the value of count does not get an error after joining a synchronization block while(count>0) {//synchronized (locobj)// {// // // // }GetTicket (); } //handlers after the thread endsSystem.out.println (Thread.CurrentThread (). GetName () + "execution end \ n"); } //defines a synchronization method This method can only be executed by one thread at a time, and another line friend can execute Public synchronized voidGetTicket () {if(count>0) {Count--; System.out.println (Thread.CurrentThread (). GetName ()+ "sell one ticket," + "remaining votes:" +count + "\ n"); Thread.yield (); } Else{flag=false; } } }
Ticketsaler class
PackageEx7_ticketsaler; Public classTicketsaler { Public Static voidMain (string[] args) {//TODO auto-generated Method StubSystem.out.println ("Start ticket \ n"); intn = 10; Thread [] Threads=NewThread[n]; Ticket Ticket=NewTicket (); for(inti=0;i<n;i++) {Threads[i]=NewThread (ticket); Threads[i].setname ("Ticketing window" +i); Threads[i].start (); }//for (int i=0;i<n;i++)// {//System.out.println ("Thread Name" +threads[i].getname () + "\ n");// } //let the new metro execute first, control the end of the thread//Thread[0] executed before thread[1], thread[1] executed before thread[2], thread[2] executed before the main thread for(inti=n-1;i>0;i--) { Try{threads[i].join (); } Catch(interruptedexception e) {//TODO auto-generated Catch blockE.printstacktrace (); }} System.out.println ("End of ticket sales \"); }}
Java multithreading implementation of the ticket sales process