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