It's easy to start a thread in Ava, and usually we wait until the end of the task to let the thread stop itself. But sometimes you need to cancel them while the task is running, so that the thread ends quickly. There is no mechanism available for this java. But we can do this through the threading interrupt mechanism provided by Java.
First look at the thread class three and interrupt-related methods:
The public class Thread { //sends an interrupt request, sets the flag bit to the interrupt state, and does not terminate the thread run. //Other thread tries to call the method, it detects if there is permission to break the thread (normal //under no permission issues, can be ignored here) public void interrupt () {...} Detects if the flag bit is an interrupted state public Boolean isinterrupted () {...} Clears the interrupt state of the current thread's flag bit, returns whether the interrupt state is public static Boolean interrupted () {...} ...}
Since a thread break does not terminate a thread's run, how can a thread break make the terminating thread run?
We know that some methods of blocking threads will throw interruptedexception to indicate that a thread break occurs, in which case a thread break can be used to terminate the thread's operation:
public class Testinterrupt {public static void main (string[] args) {blockingqueue<object> objectqueue = new Linkedblockingqueue<object> (); Consumer Consumer = new Consumer (objectqueue); Thread t = new Thread (consumer); T.start (); Wait for the thread to start the try {thread.sleep (1000); } catch (Interruptedexception e) {e.printstacktrace (); }//Interrupt thread t.interrupt (); }}class Consumer implements runnable{private final blockingqueue<object> objectqueue; Public Consumer (blockingqueue<object> objectqueue) {if (Objectqueue = = null) {throw NE W illegalargumentexception ("MessageQueue cannot be null"); } this. Objectqueue = Objectqueue; } @Override public void Run () {Boolean isrunning = true; while (isrunning) {The try {//Take method blocks when the interrupt exception is thrown because of a thread break System.out.println (Objectqueue.take ()); } catch (Interruptedexception e) {///Once the interrupt exception is thrown, the interrupt state of the thread is cleared, this time the call//thread The isinterrupted () method returns false isrunning = false; System.out.println ("Cancelled"); } } }}
The logic of the service program executed by many tasks is similar to the example above, and this method can be used to terminate the running of the thread.
Java thread break and terminate thread run