search
HomeJavajavaTutorialUnderstanding of interrupt, interrupted and isInterrupted in Java

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.");
		}
	}
}

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.

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);
}

and the implementation of isInterrupted:

public boolean isInterrupted() {    return isInterrupted(false);
}

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);

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.");
		}
	}
}

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.

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();
         }
    }
}

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

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



Statement
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
How do I use Maven or Gradle for advanced Java project management, build automation, and dependency resolution?How do I use Maven or Gradle for advanced Java project management, build automation, and dependency resolution?Mar 17, 2025 pm 05:46 PM

The article discusses using Maven and Gradle for Java project management, build automation, and dependency resolution, comparing their approaches and optimization strategies.

How do I create and use custom Java libraries (JAR files) with proper versioning and dependency management?How do I create and use custom Java libraries (JAR files) with proper versioning and dependency management?Mar 17, 2025 pm 05:45 PM

The article discusses creating and using custom Java libraries (JAR files) with proper versioning and dependency management, using tools like Maven and Gradle.

How do I implement multi-level caching in Java applications using libraries like Caffeine or Guava Cache?How do I implement multi-level caching in Java applications using libraries like Caffeine or Guava Cache?Mar 17, 2025 pm 05:44 PM

The article discusses implementing multi-level caching in Java using Caffeine and Guava Cache to enhance application performance. It covers setup, integration, and performance benefits, along with configuration and eviction policy management best pra

How can I use JPA (Java Persistence API) for object-relational mapping with advanced features like caching and lazy loading?How can I use JPA (Java Persistence API) for object-relational mapping with advanced features like caching and lazy loading?Mar 17, 2025 pm 05:43 PM

The article discusses using JPA for object-relational mapping with advanced features like caching and lazy loading. It covers setup, entity mapping, and best practices for optimizing performance while highlighting potential pitfalls.[159 characters]

How does Java's classloading mechanism work, including different classloaders and their delegation models?How does Java's classloading mechanism work, including different classloaders and their delegation models?Mar 17, 2025 pm 05:35 PM

Java's classloading involves loading, linking, and initializing classes using a hierarchical system with Bootstrap, Extension, and Application classloaders. The parent delegation model ensures core classes are loaded first, affecting custom class loa

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Chat Commands and How to Use Them
1 months agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment