Use interrupt () to break the thread
when one thread is running, another thread can call the interrupt () method of the corresponding thread object to break it, and the method simply sets a flag in the target thread that indicates that it has been interrupted and returns immediately. It is important to note that if you simply call the interrupt () method, the thread is not actually interrupted and will continue to execute.
Public classInterrupttest { Public Static voidMain (string[] args)throwsinterruptedexception {MyThread T=NewMyThread ("MyThread"); T.start (); Thread.Sleep (100);//Sleep 100 msT.interrupt ();//Interrupt T Thread } } classMyThreadextendsThread {inti = 0; PublicMyThread (String name) {Super(name); } Public voidrun () { while(true) {//dead Loop, waiting to be interruptedSystem.out.println (GetName () + getId () + "performed" + ++i + "Times"); } } }
After running, we found that the thread T has been executing, not interrupted, the original interrupt () is deceptive, Khan! In fact, the interrupt () method is not the execution of the broken thread, but to call the method's threading object to make a tag, set its interrupt state to true, through the isinterrupted () method can get this thread state, we will make a small change to the above program:
Public classInterrupttest { Public Static voidMain (string[] args)throwsinterruptedexception {MyThread T=NewMyThread ("MyThread"); T.start (); Thread.Sleep (100);//Sleep 100 msT.interrupt ();//Interrupt T Thread } } classMyThreadextendsThread {inti = 0; PublicMyThread (String name) {Super(name); } Public voidrun () { while(!isinterrupted ()) {//the current thread has not been interrupted, the executionSystem.out.println (GetName () + getId () + "performed" + ++i + "Times"); } } }
In this case, the thread is successfully interrupted and executed. When many people implement a thread class, they add a flag flag so that the control thread stops executing, which is completely unnecessary and can be implemented perfectly by the interrupt state of the thread itself. If the thread is calling the wait (), wait (long), or wait (long, int) method of the Object class, or the class's join (), join (long), join (long, int), sleep (long), or sleep (long , int) is blocked during the method, its interrupt state is cleared, and it will receive a interruptedexception. We can catch the exception and do some processing. In addition, the thread.interrupted () method is a static method that determines the interrupt state of the current thread, and it is important to note that the interrupt state of the thread is purged by the method. In other words, if the method is called twice in a row, the second call will return False (except in the case where the current thread is interrupted again until the first call has cleared its break state and the second call has finished verifying the break state).
(4) Java thread interrupt