[Javase] Multithreading (ticketing example)

Source: Internet
Author: User

Requirements: Simple ticket purchase procedure, multiple window selling tickets, multi-threading

Define a class Ticket implement The Runnable interface,

Defines the number of votes for a member property int type nums

Implement the Run () method,in therun method

while (true) of the Dead loop, print nums--

Get Ticket object,new out

Get the Thread () object,new out, construct parameter:runable Object

Call the start () method of the thread object to open the thread

Thread security issues at this time, using synchronized Synchronous code blocks to resolve security issues

Avoid deadlock problems, synchronization is nested in sync, and locks are different

classTicketImplementsRunnable {Private intNums = 100; @Override Public voidrun () { while(true) {            synchronized( This) {                if(Nums > 0) {                    Try{Thread.Sleep (10); } Catch(Exception e) {e.printstacktrace (); } System.out.println (Thread.CurrentThread (). GetName ()+ "= = =" + (nums--)); }Else{                     Break; }            }        }    }} Public classTicketdemo {/**     * @paramargs*/     Public Static voidMain (string[] args) {Ticket Ticket=NewTicket (); NewThread (Ticket). Start (); NewThread (Ticket). Start (); NewThread (Ticket). Start (); NewThread (Ticket). Start (); }}

[Javase] Multithreading (ticketing example)

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.