It's easy to start a thread in Java, 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:
Public classThread {//make an interrupt request, set the flag bit to the interrupt state,does not terminate the thread run.
///other thread tries to call the method, it detects if there is permission to break the thread (normal
There will be no permissions issues, which can be ignored here) Public voidinterrupt () {...} //detects if the flag bit is an interrupted state Public Booleanisinterrupted () {...} //clears the interrupt state of the current thread's flag bit and returns whether it is an interrupt state Public Static Booleaninterrupted () {...} ...}
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 classTestinterrupt { Public Static voidMain (string[] args) {Blockingqueue<Object> Objectqueue =NewLinkedblockingqueue<object>(); Consumer Consumer=NewConsumer (Objectqueue); Thread T=NewThread (consumer); T.start (); //waiting for thread to start Try{Thread.Sleep (1000); } Catch(interruptedexception e) {e.printstacktrace (); } //break thread inT.interrupt (); }}classConsumerImplementsrunnable{Private FinalBlockingqueue<object>Objectqueue; PublicConsumer (blockingqueue<object>objectqueue) { if(Objectqueue = =NULL) { Throw NewIllegalArgumentException ("MessageQueue cannot be null"); } This. Objectqueue =Objectqueue; } @Override Public voidrun () {BooleanIsRunning =true; while(isrunning) { Try { //The take method blocks when an interrupt exception is thrown because of a thread breakSystem.out.println (Objectqueue.take ()); } Catch(Interruptedexception e) {
once the interrupt exception is thrown, the interrupt state of the thread is cleared, which is called
The // thread 's 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 concurrency programming thread break and terminate thread run