Understanding 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:
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,说明你能处理这个异常,你不希望上层调用者看到这个中断)。

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

In this article, we have kept the most asked Java Spring Interview Questions with their detailed answers. So that you can crack the interview.

Java 8 introduces the Stream API, providing a powerful and expressive way to process data collections. However, a common question when using Stream is: How to break or return from a forEach operation? Traditional loops allow for early interruption or return, but Stream's forEach method does not directly support this method. This article will explain the reasons and explore alternative methods for implementing premature termination in Stream processing systems. Further reading: Java Stream API improvements Understand Stream forEach The forEach method is a terminal operation that performs one operation on each element in the Stream. Its design intention is

Guide to TimeStamp to Date in Java. Here we also discuss the introduction and how to convert timestamp to date in java along with examples.

Capsules are three-dimensional geometric figures, composed of a cylinder and a hemisphere at both ends. The volume of the capsule can be calculated by adding the volume of the cylinder and the volume of the hemisphere at both ends. This tutorial will discuss how to calculate the volume of a given capsule in Java using different methods. Capsule volume formula The formula for capsule volume is as follows: Capsule volume = Cylindrical volume Volume Two hemisphere volume in, r: The radius of the hemisphere. h: The height of the cylinder (excluding the hemisphere). Example 1 enter Radius = 5 units Height = 10 units Output Volume = 1570.8 cubic units explain Calculate volume using formula: Volume = π × r2 × h (4

PHP and Python each have their own advantages, and the choice should be based on project requirements. 1.PHP is suitable for web development, with simple syntax and high execution efficiency. 2. Python is suitable for data science and machine learning, with concise syntax and rich libraries.

PHP is a scripting language widely used on the server side, especially suitable for web development. 1.PHP can embed HTML, process HTTP requests and responses, and supports a variety of databases. 2.PHP is used to generate dynamic web content, process form data, access databases, etc., with strong community support and open source resources. 3. PHP is an interpreted language, and the execution process includes lexical analysis, grammatical analysis, compilation and execution. 4.PHP can be combined with MySQL for advanced applications such as user registration systems. 5. When debugging PHP, you can use functions such as error_reporting() and var_dump(). 6. Optimize PHP code to use caching mechanisms, optimize database queries and use built-in functions. 7

Java is a popular programming language that can be learned by both beginners and experienced developers. This tutorial starts with basic concepts and progresses through advanced topics. After installing the Java Development Kit, you can practice programming by creating a simple "Hello, World!" program. After you understand the code, use the command prompt to compile and run the program, and "Hello, World!" will be output on the console. Learning Java starts your programming journey, and as your mastery deepens, you can create more complex applications.

Spring Boot simplifies the creation of robust, scalable, and production-ready Java applications, revolutionizing Java development. Its "convention over configuration" approach, inherent to the Spring ecosystem, minimizes manual setup, allo
