简体   繁体   English

Java 中的 InterruptedException 是什么?

[英]What is an InterruptedException in Java?

I have seen many times in my code that I get an Interrupted Exception.我在我的代码中多次看到我得到一个中断的异常。 What is that, and how do I fix it?那是什么,我该如何解决?

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.由于我不知道您对Java了解多少, Java是如何工作的以及并发是什么,我将尝试在几乎不需要背景信息的情况下尽可能多地进行解释。


At first we're going to take a look at Oracle's documentation of the InterruptedException .首先,我们将看一下 Oracle 的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 aThread works.在回答这个问题之前,您必须初步了解Thread工作原理。

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.如果你启动一个普通的 java 程序, main()方法是在自己的线程 1 中创建的。你所做的一切都将在这个线程中执行。 Every class you create, every method you call and basically everything that originated from main() .您创建的每个类、您调用的每个方法以及基本上所有源自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.但是如果你创建一个Thread ,它会在自己的线程 2 中run() 。 你在run()方法中所做的一切都将在线程 2 中执行。


What happens if you create a new Thread ?如果你创建一个新的Thread会发生什么?

The join() method is called.调用join()方法。

The join() method starts the thread and run() is being executed. join()方法启动线程并且run()正在被执行。

There's not only the join() method with no parameters but also a join(long millis) with a parameter.不仅有没有参数的join()方法,还有带参数的join(long millis)


When and why is it thrown?何时以及为何抛出?

As Rahul Iyer already said there's a variety of reasons.正如 Rahul Iyer 已经说过的,有多种原因。 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.当超过超时时,确实可以抛出InterruptedException This happens when the join(long millis) is called.当调用join(long millis)时会发生这种情况。 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). (从第 769 行到第 822 行)。

  1. OS is stopping the thread操作系统正在停止线程

Maybe the O perating S ystem (Windows, Linux, Android, etc.) decided to stop the program.也许操作摄像体系(在Windows,Linux,Android等),决定停止该程序。 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 Thread抛出 InterruptedException

    For example you're connected to the internet and you're reading something and the internet disconnects suddenly.例如,您已连接到 Internet,正在阅读某些内容,但 Internet 突然断开连接。

  2. interrupt() is called interrupt()被调用

    As already mentioned, an InterruptedException is also thrown, when you call the interrupt() on any Thread (quite logical).如前所述,当您在任何Thread上调用interrupt()时,也会抛出InterruptedException (非常合乎逻辑)。


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.将它包装在trycatch ,声明该方法throws它,记录它等。

This may be the best resource for you: Handling InterruptedException in Java .这可能是最适合您的资源: Handling InterruptedException in Java

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

public class InterruptedException extends Exception公共类 InterruptedException 扩展异常

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:您可以在此处遵循 oracles 教程:

https://docs.oracle.com/javase/tutorial/essential/concurrency/interrupt.html 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.修复它的方法可能是用 Try-Catch 块包围导致它的代码并处理异常。 For example (from Oracles tutorial):例如(来自 Oracles 教程):

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.上面的链接中有更多关于如何处理不同场景的示例。

Shortly, InterruptedException is usually thrown when a thread or some other action is interrupted.很快,当线程或其他一些操作被中断时,通常会抛出 InterruptedException。 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.线程是在做某事还是在睡觉都没有关系,您可以通过调用interrupt() 或其他方法来以编程方式执行此操作并在“被占用”线程上执行此操作,该线程用于睡眠。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM