PackageTry51.thread.safe;Importjava.util.ArrayList;ImportJava.util.Random;ImportJava.util.concurrent.ExecutorService;Importjava.util.concurrent.Executors; Public classThreadsafedemo { Public Static voidMain (string[] args) {//all votesarraylist<thread> LST =NewArraylist<>(); Lst.add (NewThread (NewTickets ("Online ticketing"))); Lst.add (NewThread (NewTickets ("mobile app ticketing"))); Lst.add (NewThread (NewTickets ("Field window ticketing"))); //randomly generate a client typeRandom Rdom =NewRandom (); //set up a pool of threadsExecutorservice es = executors.newfixedthreadpool (100); //Analog has 15 clients to buy tickets for(inti = 0; I < 15; i++) { intindex = Rdom.nextint (3); Thread Thread=Lst.get (index); //buy ticket thread into thread pooles.submit (thread); } //Close the thread poolEs.shutdown (); }}/** * * @authorLZTKDR **/classTicketsImplementsRunnable {//Security Lock Object Public StaticObject locker =NewObject (); //static number of votes (fixed) Public Static intTicketcount = 10; PublicString name; /** * * @paramName client votes*/ Publictickets (String name) { This. Name =name; } @Override Public voidrun () {//line Lock queue type ticketing synchronized(locker) {Try { //200 milliseconds to simulate a ticket purchaseThread.Sleep (200); } Catch(interruptedexception e) {e.printstacktrace (); } if(Ticketcount > 0) {System.out.println ( This. name + "\ t sell 11 sheets, remaining \ t" + (--ticketcount)); } Else{System.out.println ( This. name + "\ t got the ticket!!!" "); } } }}
Simulated thread-safe ticketing case (Java)