We generally use multi-threading, which is the dead loop of the while, want to end the thread, just exit the dead loop to
When the sleep () method or the Wait () method is called in the thread , the current thread goes into a frozen state and the thread ends
Calling the interrupt () method of the Thread object can be forced to thaw, at which point the run () method needs to capture the Interruptexception The exception, and then processing it, you can close the thread.
Call the Setdaemon () method of the Thread object , Parameter:true
The daemon thread is a background thread, and the background thread ends automatically when the current thread is all over.
classTicketImplementsRunnable {Private intNums = 100; @Override Public voidrun () { while(true) { synchronized( This) { if(Nums > 0) { Try{Thread.Sleep (100); } 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 (); Thread T1=NewThread (ticket); Thread T2=NewThread (ticket); T1.setdaemon (true); T2.setdaemon (true); T1.start (); T2.start (); //The main thread executes in 1 seconds, and the other daemons will end before they're finished. while(true){ Try{Thread.Sleep (1000); Break; } Catch(Exception e) {e.printstacktrace (); } } }}
[Javase] Multithreading (daemon thread)