Mock ticketing Procedure (practice on multi-threaded sharing)

Source: Internet
Author: User

Inheriting tread to implement multithreading, the written class is a subclass of thread, so the object generated with this custom class is a thread, and by implementing a Runnable implementation class to implement multi-threading, you also declare a thread class object, The object of this Runnable implementation class is passed into a constructor of the thread class to declare a thread object, which is a true thread object, and can be shared by passing an object of the same Runnable implementation class into the thread constructor.

Code implementation:

 PackageThreaddemo; Public classTickets_sale { Public Static voidMain (String[]args) {Sell Sell=NewSell (); NewThread (Sell, "window one"). Start (); NewThread (Sell, "window two"). Start (); NewThread (Sell, "window three"). Start (); NewThread (Sell, "window four"). Start (); }    }classSellImplementsrunnable{Private  inttickets_amount=100;  Public synchronized voidSellticket () {Tickets_amount--; if(tickets_amount>0) {System.out.println (Thread.CurrentThread (). GetName ()+ "sell one, more tickets have" +tickets_amount+ "Zhang"); System.out.println ("Making a ticket."); Try{Thread.Sleep (500); System.out.println ("Ticketing Success"); } Catch(interruptedexception e) {System.out.println ("Thread Sleep Exception");        E.printstacktrace (); } }} @Override Public voidrun () { while(true){            if(tickets_amount>0) {sellticket (); }Else if(tickets_amount<=0) {System.out.println ("The tickets are sold out."); return; }Else{System.out.println ("System Error"); return; }        }    }}

Mock ticketing Procedure (practice on multi-threaded sharing)

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.