Home > Java > javaTutorial > body text

Understanding of interrupt, interrupted and isInterrupted in Java

高洛峰
Release: 2016-11-22 12:59:31
Original
2615 people have browsed it

Today I saw that the isInterrupted method of the Thread class can obtain the interrupt status of the thread:

Understanding of interrupt, interrupted and isInterrupted in Java

So I wrote an example to verify it:

public class Interrupt {	public static void main(String[] args) throws Exception {
		Thread t = new Thread(new Worker());
		t.start();
		
		Thread.sleep(200);
		t.interrupt();
		
		System.out.println("Main thread stopped.");
	}	
	public static class Worker implements Runnable {		public void run() {
			System.out.println("Worker started.");			
			try {
				Thread.sleep(500);
			} catch (InterruptedException e) {
				System.out.println("Worker IsInterrupted: " + 
						Thread.currentThread().isInterrupted());
			}
			
			System.out.println("Worker stopped.");
		}
	}
}
Copy after login

The content is very simple answer: the main thread main starts a sub-thread Worker, and then Let the worker sleep for 500ms, and main sleep for 200ms. Then main calls the interrupt method of the worker thread to interrupt the worker. After the worker is interrupted, the interrupt status is printed. The following is the execution result:

Worker started.
Main thread stopped.
Worker IsInterrupted: falseWorker stopped.
Copy after login

Worker has obviously been interrupted, but the isInterrupted() method returned false. Why?

After searching around on stackoverflow, I found that some netizens mentioned that you can view the JavaDoc (or source code) of the method that throws InterruptedException, so I checked the documentation of the Thread.sleep method. The doc describes this InterruptedException exception like this :

InterruptedException - if any thread has interrupted the current thread. The interrupted status of the current thread is cleared when this exception is thrown.

Notice the following sentence "When this exception is thrown, the interrupted status has been cleared Clear". So the isInterrupted() method should return false. But sometimes, we need the isInterrupted method to return true. What should we do? Here we will first talk about the difference between interrupt, interrupted and isInterrupted: The

interrupt method is used to interrupt the thread, and the status of the thread calling this method will be set to the "interrupted" status. Note: Thread interrupt only sets the interrupt status bit of the thread and does not stop the thread. The user needs to monitor the status of the thread and handle it himself. The method that supports thread interruption (that is, the method that throws InterruptedException after the thread is interrupted, such as sleep here, and Object.wait and other methods) is to monitor the interruption status of the thread. Once the interruption status of the thread is set to "interrupted status" , an interrupt exception will be thrown. This view can be confirmed by this article:

interrupt() merely sets the thread's interruption status. Code running in the interrupted thread can later poll the interrupted status to see if it has been requested to stop what it is doing

See again Look at the implementation of the interrupted method:

public static boolean interrupted() {    return currentThread().isInterrupted(true);
}
Copy after login

and the implementation of isInterrupted:

public boolean isInterrupted() {    return isInterrupted(false);
}
Copy after login

One of these two methods is static and the other is not, but they are actually calling the same method, except that the parameter passed in by the interrupted method is true. The parameter passed in by inInterrupted is false. So what does this parameter mean? Let’s take a look at the implementation of the isInterrupted(boolean) method:

/**
 * Tests if some Thread has been interrupted.  The interrupted state
 * is reset or not based on the value of ClearInterrupted that is
 * passed.
 */private native boolean isInterrupted(boolean ClearInterrupted);
Copy after login

This is a native method. It doesn’t matter if you can’t see the source code. The parameter name ClearInterrupted has clearly expressed the function of this parameter—whether to clear the interrupt status. The annotation of the method also clearly expresses that "the interrupt status will be reset based on the passed ClearInterrupted parameter value." Therefore, the static method interrupted will clear the interrupt status (the passed parameter ClearInterrupted is true), but the instance method isInterrupted will not (the passed parameter ClearInterrupted is false).

Back to the previous question: Obviously, if you want the isInterrupted method to return true, you can restore the interrupted state by calling the interrupt() method again before calling the isInterrupted method:

public class Interrupt  {	public static void main(String[] args) throws Exception {
		Thread t = new Thread(new Worker());
		t.start();
		
		Thread.sleep(200);
		t.interrupt();
		
		System.out.println("Main thread stopped.");
	}	
	public static class Worker implements Runnable {		public void run() {
			System.out.println("Worker started.");			
			try {
				Thread.sleep(500);
			} catch (InterruptedException e) {
				Thread curr = Thread.currentThread();				//再次调用interrupt方法中断自己,将中断状态设置为“中断”
				curr.interrupt();
				System.out.println("Worker IsInterrupted: " + curr.isInterrupted());
				System.out.println("Worker IsInterrupted: " + curr.isInterrupted());
				System.out.println("Static Call: " + Thread.interrupted());//clear status
				System.out.println("---------After Interrupt Status Cleared----------");
				System.out.println("Static Call: " + Thread.interrupted());
				System.out.println("Worker IsInterrupted: " + curr.isInterrupted());
				System.out.println("Worker IsInterrupted: " + curr.isInterrupted());
			}
			
			System.out.println("Worker stopped.");
		}
	}
}
Copy after login

Execution result:

Worker started.
Main thread stopped.
Worker IsInterrupted: true
Worker IsInterrupted: true
Static Call: true
---------After Interrupt Status Cleared----------
Static Call: false
Worker IsInterrupted: false
Worker IsInterrupted: false
Worker stopped.
Copy after login

You can also see from the execution results that the first two calls to the isInterrupted method return true, indicating that the isInterrupted method will not change the interrupt status of the thread, and then the static interrupted() method is called, and the first return true, indicating that the thread was interrupted, and false for the second time, because the interruption status has been cleared during the first call. The last two calls to the isInterrupted() method will definitely return false.

So, in what scenario do we need to interrupt the thread (reset the interrupt status) in the catch block?

The answer is: If InterruptedException cannot be thrown (just like the Thread.sleep statement here is placed in Runnable's run method, this method does not allow any checked exceptions to be thrown), but you want to tell the upper caller what happened here When an interrupt occurs, the interrupt status can only be reset in catch.

If you catch InterruptedException but cannot rethrow it, you should preserve evidence that the interruption occurred so that code higher up on the call stack can learn of the interruption and respond to it if it wants to. This task is accomplished by calling interrupt( ) to "reinterrupt" the current thread, as shown in Listing 3.

Listing 3: Restoring the interrupted status after catching InterruptedException

public class TaskRunner implements Runnable {    private BlockingQueue<Task> queue; 
    public TaskRunner(BlockingQueue<Task> queue) { 
        this.queue = queue; 
    } 
    public void run() { 
        try {             while (true) {
                 Task task = queue.take(10, TimeUnit.SECONDS);
                 task.execute();
             }
         } catch (InterruptedException e) { 
             // Restore the interrupted status
             Thread.currentThread().interrupt();
         }
    }
}
Copy after login

那么问题来了:为什么要在抛出InterruptedException的时候清除掉中断状态呢?

这个问题没有找到官方的解释,估计只有Java设计者们才能回答了。但这里的解释似乎比较合理:一个中断应该只被处理一次(你catch了这个InterruptedException,说明你能处理这个异常,你不希望上层调用者看到这个中断)。



Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template