Thread.currentThread.interrupt () only works on blocking threads,
When a thread is blocked, the interrupt method is called, and the thread gets an interrupt exception that can be exited by processing the exception
There is no effect on the running thread.
First look at the collection of other people's articles, a comprehensive understanding of the following Java interrupts: interrupt thread
The thread's Thread.Interrupt () method is the interrupt thread, which will set the break status bit of the threads, that is, set to true, whether the interrupted result thread is dead or waiting for a new task or continues to the next step, depending on the program itself. The thread periodically detects the interrupt flag bit to determine if the thread should be interrupted (the interrupt flag value is true). It does not break a running thread like the Stop method does. To determine if a thread has been interrupted
To determine if a thread has been sent an interrupt request, use the Thread.CurrentThread (). Isinterrupted () method (because it does not immediately clear the interrupt flag bit after it sets the thread interrupt flag bit to true, that is, the interrupt mark is not set to false) , rather than using thread.interrupted () (the method call will clear the interrupt flag bit, or reset to False) method to determine, the following is the way the thread interrupts in the loop:
while (! Thread.CurrentThread (). isinterrupted () && more work to do
}
How to break the thread
If a thread is in a blocking state (such as when a thread calls Thread.Sleep, Thread.Join, thread.wait, condition.await in 1.5, and I/O operations on an interruptible channel can go into a blocking state), The thread will check for interrupt indication if the interrupt is identified as true, then the I/O on these blocking methods (sleep, join, wait, condition.await in 1.5, and the Interruptible channel Action method), the interruptedexception exception is thrown at the call, and the interrupt flag bit of the thread is cleared immediately after the exception is thrown, which is reset to false. The exception is thrown in order for the thread to wake up from the blocking state and give the programmer enough time to handle the interrupt request before ending the thread.
Note that synchronized cannot be interrupted in the process of being locked, meaning that if a deadlock is created, it is impossible to be interrupted (refer to the test example below). The same is true of the Reentrantlock.lock () method, which is similar to the synchronized function, which is also non-interruptible, that is, if a deadlock occurs, the Reentrantlock.lock () method cannot be terminated, and if the call is blocked, It blocks until it gets to the lock. However, if the Trylock method with timeout is called Reentrantlock.trylock (long timeout, timeunit unit), a Interruptedexception exception will be thrown if the thread is interrupted while waiting. This is a very useful feature because it allows the program to break the deadlock. You can also call the reentrantlock.lockinterruptibly () method, which is equivalent to a timeout set to an infinite Trylock method.
There is no language requirement that an interrupted thread should terminate. Interrupts a thread just to cause the thread to notice that the interrupted thread can decide how to respond to the interrupt. Some threads are so important that they should ignore interrupts and continue execution after they have handled the thrown exception, but more generally, a thread will treat interrupts as a termination request, a thread whose run method follows the following form:
public void Run () {
try {
...
/* * Regardless of whether the loop has called thread blocking methods such as sleep, join, wait, here still need to add
*! Thread.CurrentThread (). isinterrupted () condition, while exiting the loop after throwing an exception,
is superfluous if the blocking method is called, but it is more secure and timely if the blocking methods are invoked without blocking.
*
/while (! Thread.CurrentThread (). isinterrupted () && more work to do
}
catch ( Interruptedexception e) {
//The thread was interrupted during wait or sleep
} finally {
//The thread finishes some cleanup work before the end}
}
Above is the while loop in the try block, if the try in the while loop, because it is in the catch block to reset the interrupt flag, because the throw interruptedexception exception, the interrupt indicator bit will be automatically cleared, this should be the case:
public void Run () {while
(! Thread.CurrentThread (). isinterrupted () && more work to do) {
try {
...
Sleep (delay);
} catch (Interruptedexception e) {
thread.currentthread (). interrupt ();//Reset Interrupt Flag}}
}
How to handle the underlying interrupt exception
Also do not capture the interruptedexception exception in your underlying code after not processing, will be handled improperly, as follows:
void Mysubtask () {
...
try{
Sleep (delay);
} catch (Interruptedexception e) {}//do not do this ...
}
If you do not know what to do after throwing a interruptedexception exception, then you have the following good advice to deal with:
1. In the catch clause, call Thread.currentThread.interrupt () to set the interrupt state (because the interrupt flag is cleared after the exception is thrown), allowing the outside world to Judge Thread.CurrentThread (). Isinterrupted () flag to decide whether to terminate the thread or continue, this should be done:
void Mysubtask () {
...
try {
sleep (delay);
} catch (Interruptedexception e) {
thread.currentthread (). isinterrupted ();
}
...
}
2, or, better yet, do not use try to catch such an exception and let the method throw it directly:
void Mysubtask () throws Interruptedexception {...
Sleep (delay);
...
}
Interrupt Application
interrupts a non-blocking thread using interrupt semaphore
The most recommended way to break a thread in the
is to use a shared variable (GKFX variable) to signal that the thread must stop the running task. The thread must periodically check this variable and then abort the task in an orderly manner. Example2 describes this approach:
Class Example2 extends Thread {volatile Boolean stop = false;//thread interrupt semaphore public static void Main (String args[]) t
Hrows Exception {Example2 thread = new Example2 ();
SYSTEM.OUT.PRINTLN ("Starting thread ...");
Thread.Start ();
Thread.Sleep (3000);
SYSTEM.OUT.PRINTLN ("Asking Thread to stop ...");
Set Interrupt semaphore Thread.stop = true;
Thread.Sleep (3000);
SYSTEM.OUT.PRINTLN ("Stopping application ..."); The public void Run () {//Every second detects the interrupt semaphore while (!stop) {System.out.println ("Thread is Runn
ing ... ");
Long time = System.currenttimemillis (); /* * Use the While loop to simulate the sleep method, where sleep is not used, otherwise the interruptedexception exception is thrown when blocking and exits the loop, so while the stop condition is not
Execution, * loss of meaning. */while ((System.currenttimemillis ()-time <)) {}} System.out.println ("Thread Exiti
ng under request ... "); }
}
using Thread.Interrupt () to interrupt a non-blocking state thread
Although Example2 this method requires some coding, it is not difficult to implement. At the same time, it gives threads the opportunity to do the necessary cleanup work. One thing to note here is that you need to define a shared variable as a volatile type or to block all access to it into the synchronized blocks/methods (synchronized Blocks/methods). Above is a common practice for interrupting a non-blocking thread, but the non-instrumented isinterrupted () condition is more concise:
class Example2 extends Thread {public static void main (String args[]) throws Exception
{Example2 thread = new Example2 ();
SYSTEM.OUT.PRINTLN ("Starting thread ...");
Thread.Start ();
Thread.Sleep (3000);
SYSTEM.OUT.PRINTLN ("Asking Thread to stop ...");
Make an interrupt request Thread.Interrupt ();
Thread.Sleep (3000);
SYSTEM.OUT.PRINTLN ("Stopping application ..."); The public void Run () {//Every second detects if the interrupt flag is set while (!
Thread.CurrentThread (). isinterrupted ()) {System.out.println ("Thread is running ...");
Long time = System.currenttimemillis ();
Use while loop to simulate sleep while ((System.currenttimemillis ()-time < 1000)) {}}
System.out.println ("Thread exiting under request ..."); }
}
So far everything went well. However, what happens when a thread waits for certain events to occur and is blocked. Of course, if a thread is blocked, it cannot check for shared variables and cannot stop. This can happen in many cases, such as when calling Object.wait (), serversocket.accept (), and datagramsocket.receive (), just a few.
They are all likely to block threads permanently. Even if a timeout occurs, it is not feasible and inappropriate to wait until the timeout expires, so a mechanism is used to allow the thread to exit the blocked state earlier. Here's a look at interrupt blocking threading technology. blocking state threads with Thread.Interrupt () interrupts
The Thread.Interrupt () method does not break a running thread. What this method actually does is to set the interrupt flag bit of the thread, throw an exception interruptedexception where the threads are blocked (such as call sleep, wait, join, etc.), and the interrupt state will be cleared so that the thread exits the blocked state. Here are the specific implementations:
Class Example3 extends thread {public static void main (String args[]) throws Exception {Example3 thread = NE
W Example3 ();
SYSTEM.OUT.PRINTLN ("Starting thread ...");
Thread.Start ();
Thread.Sleep (3000);
SYSTEM.OUT.PRINTLN ("Asking Thread to stop ...");
Thread.Interrupt ();//wait for interrupt semaphore set and then call Thread.Sleep (3000);
SYSTEM.OUT.PRINTLN ("Stopping application ..."); } public void Run () {while (!
Thread.CurrentThread (). isinterrupted ()) {System.out.println ("Thread running ..."); try {/* * If the thread is blocked, it will not check the interrupt semaphore stop variable, so thread.interrupt () * will cause the blocking thread to be blocked from the place Throws an exception, letting the blocking thread escape from the blocking state, and * handling the exception block for corresponding processing */thread.sleep (1000);//thread blocking if thread
Receive interrupt operation signal will throw exception} catch (Interruptedexception e) {System.out.println ("Thread interrupted ..."); /* * If the thread is calling the object.wait () partymethod, or the join (), sleep () method of the class is blocked, its interrupt state is cleared/System.out.println (this.
Isinterrupted ());//False//In the non-interruption of the decision, if you need to be true in the thread, you need to reset the interrupt bit, if//do not need to call
Thread.CurrentThread (). interrupt ();
}} System.out.println ("Thread exiting under request ..."); }
}
Once the Thread.Interrupt () in the Example3 is called, the thread receives an exception and then escapes the blocking state and determines that it should stop. We can also use shared semaphores to replace them! Thread.CurrentThread (). isinterrupted () condition, but not as concise as it is. deadlock state thread cannot be interrupted
Example4 tried to break two threads in a deadlock state, but none of the two lines received any interrupt signal (throwing an exception), so the interrupt () method was not able to break the deadlock thread because the locked position could not throw an exception at all:
Class Example4 extends Thread {public static void main (String args[]) throws Exception {final Object lock1 =
New Object ();
Final Object Lock2 = new Object ();
Thread thread1 = new Thread () {public void run () {Deathlock (lock1, Lock2);
}
}; Thread thread2 = new Thread () {public void run () {///note, here is a swap position deathlock
(Lock2, LOCK1);
}
};
SYSTEM.OUT.PRINTLN ("Starting thread ...");
Thread1.start ();
Thread2.start ();
Thread.Sleep (3000);
SYSTEM.OUT.PRINTLN ("Interrupting thread ...");
Thread1.interrupt ();
Thread2.interrupt ();
Thread.Sleep (3000);
SYSTEM.OUT.PRINTLN ("Stopping application ...");
} static void Deathlock (object Lock1, Object Lock2) {try {synchronized (LOCK1) { Thread.Sleep (10);//Will not die here synchronized (loCK2) {//Will be locked here, although blocked, but will not throw abnormal System.out.println (Thread.CurrentThread ());
}}} catch (Interruptedexception e) {e.printstacktrace ();
System.exit (1); }
}
}
Interrupt I/O operations
However, what happens if the thread is blocked while the I/O operation is in progress. I/O operations can block threads for a considerable amount of time, especially when it comes to network applications. For example, the server may need to wait for a request, or a network application may have to wait for the remote host to respond.
Implement this INTERRUPTIBL