What is an InterruptedException in Java?

拥有回忆 提交于 2021-02-08 11:21:25

问题


I have seen many times in my code that I get an Interrupted Exception. What is that, and how do I fix it?


回答1:


Since I don't know how much you know about Java, how java works exactly and what's concurrency, I'll try to explain as much as possible with nearly no background information needed.


At first we're going to take a look at Oracle's documentation of the InterruptedException.

Thrown when a thread is waiting, sleeping, or otherwise occupied, and the thread is interrupted, either before or during the activity. [...]


What does this mean?

Before answering this question you have to rudimentary understand how a Thread works.

A thread is originally just a piece of code that can be managed seperately from other threads. It can run at the same time (see concurrency), run scheduled, etc.


Example

If you start a normal java program the main() method is created in an own thread 1. Everything you do will be executed in this thread. Every class you create, every method you call and basically everything that originated from main().

But if you create a Thread, it runs in an own thread 2. Everything you do in the run() method will be executed in thread 2.


What happens if you create a new Thread?

The join() method is called.

The join() method starts the thread and run() is being executed.

There's not only the join() method with no parameters but also a join(long millis) with a parameter.


When and why is it thrown?

As Rahul Iyer already said there's a variety of reasons. I'm picking some of them to get you a feeling when they're called.

  1. Timeout

The InterruptedException can be indeed thrown when a timeout was exceeded. This happens when the join(long millis) is called. The parameter specifies that the thread can run for the given amount of milliseconds. When the thread exceeds this timeout it is interrupted. source (from line 769 to line 822).

  1. OS is stopping the thread

Maybe the Operating System (Windows, Linux, Android, etc.) decided to stop the program. Why? To free resources, your program was mistaken as a virus, hardware is shutting down, the user manually closed it, etc.

  1. An InterruptedException is thrown in the Thread

    For example you're connected to the internet and you're reading something and the internet disconnects suddenly.

  2. interrupt() is called

    As already mentioned, an InterruptedException is also thrown, when you call the interrupt() on any Thread (quite logical).


How to handle it?

You can/should handle it like every other exception. Wrap it in a try and catch, declare that the method throws it, log it, etc.

This may be the best resource for you: Handling InterruptedException in Java.




回答2:


From the docs: https://docs.oracle.com/javase/7/docs/api/java/lang/InterruptedException.html

public class InterruptedException extends Exception

Thrown when a thread is waiting, sleeping, or otherwise occupied, and the thread is interrupted, either before or during the activity. Occasionally a method may wish to test whether the current thread has been interrupted, and if so, to immediately throw this exception. The following code can be used to achieve this effect:

if (Thread.interrupted())  // Clears interrupted status!
      throw new InterruptedException();

You can follow oracles tutorial here:

https://docs.oracle.com/javase/tutorial/essential/concurrency/interrupt.html

The way to fix it is probably to surround the code that causes it with a Try-Catch block and handle the exception. For example (from Oracles tutorial):

for (int i = 0; i < importantInfo.length; i++) {
    // Pause for 4 seconds
    try {
        Thread.sleep(4000);
    } catch (InterruptedException e) {
        // We've been interrupted: no more messages.
        return;
    }
    // Print a message
    System.out.println(importantInfo[i]);
}

There are more examples in the above link on how to handle different scenarios.




回答3:


Shortly, InterruptedException is usually thrown when a thread or some other action is interrupted. It does not matter if the thread was doing something or sleeping, you can programmatically do this by calling interrupt() or other methods on and "occupied" thread, who is for sleeping.



来源:https://stackoverflow.com/questions/64741016/what-is-an-interruptedexception-in-java

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!