Simulated thread-safe ticketing case (Java)

Source: Internet
Author: User
Tags lock queue ticket

 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)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.