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)