Use thread. Interrupt () to interrupt the thread
As described in listing a, the thread. Interrupt () method does not interrupt a running thread. In fact, this method throws an interrupt signal when the thread is blocked, so that the thread can exit the blocking state. More specifically, if the thread is. wait, thread. join and thread. if sleep is blocked by one of the three methods, it will receive an interrupt exception (interruptedexception) to terminate the blocked state early.
Therefore, if the thread is blocked by the preceding methods, the correct way to stop the thread is to set the shared variable and call interrupt () (note that the variable should be set first ). If the thread is not blocked, calling interrupt () will not work; otherwise, the thread will get an exception (the thread must be prepared to handle this situation in advance) and then escape from the blocking state. In either case, the last thread checks the shared variable and stops. The listing c example describes the technology.
Listing cClass example3 extends thread {volatile Boolean stop = false; public static void main (string ARGs []) throws exception {example3 thread = new example3 (); system. out. println ("Starting thread... "); thread. start (); thread. sleep (1, 3000); system. out. println ("asking thread to stop... "); thread. stop = true; // If the thread is blocked, the thread variable will not be checked. interrupt (); thread. sleep (1, 3000); system. out. println ("Sto Pping application... "); // system. Exit (0);} public void run () {While (! Stop) {system. out. println ("thread running... "); try {thread. sleep (1000);} catch (interruptedexception e) {system. out. println ("thread interrupted... ") ;}} system. out. println ("thread exiting under request... ");}} |
Once the thread. Interrupt () in listing C is called, the thread receives an exception and escapes the blocking status and determines that it should be stopped. Run the above code to get the following output:
Starting thread...Thread running...Thread running...Thread running...Asking thread to stop...Thread interrupted...Thread exiting under request...Stopping application... |