Queue up for tickets

Source: Internet
Author: User
Tags ticket

Requirement: Assume the total number of votes is 100 sheets
Suppose there are 5 people in line to sell tickets, and only one person can buy tickets at the same time.
After the tickets are sold, the number of votes is reduced.

Code:

/** *  */ Packagecom.niit.homework;/** * @author: Annie * @date: June 16, 2016 * @description: Assuming the total number of votes is 100 fake there are 5 people lined up to sell tickets at the same time only There's a man who buys a ticket and sells it, and the number of votes goes down.*/ Public classTicketdemoImplementsRunnable {intTickt = 100; StaticString [] name = {"Zhang San", "John Doe", "Wang er", "leper", "Zhao Si"}; @Override Public voidrun () {BooleanFlag =true ;  while(flag) {synchronized( This) {                 for(intj = 0; J <5; J + +) {                    if(Thread.CurrentThread (). GetName (). Equals (Name[j])) {--tickt; System.out.println (Name[j]+ "are buying tickets, others please be patient in line, and" +tickt+ "Ticket"); }                    if(Tickt <=0) {flag=false; System.out.println ("The tickets are sold out and come back tomorrow.");  Break; }                    Try{Thread.Sleep (200); } Catch(Interruptedexception e) {}}} }    }     Public Static voidMain (string[] args) {Ticketdemo ticket=NewTicketdemo (); Thread [] Threads=NewThread[5];  for(inti = 0; i < threads.length; i++) {Threads[i]=NewThread (Ticket,name[i]);        Threads[i].start (); }    }}

(Part of it):

Queue up for tickets

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.