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)