处理Java中的InterruptedException [英] Handling InterruptedException in Java

查看:111
本文介绍了处理Java中的InterruptedException的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下处理 InterruptedException 之间的区别是什么?什么是最好的方式?

What is the difference between the following ways of handling InterruptedException? What is the best way to do it?

try{
 //...
} catch(InterruptedException e) { 
   Thread.currentThread().interrupt(); 
}

try{
 //...
} catch(InterruptedException e) {
   throw new RuntimeException(e);
}

编辑:我也想知道这两种情况在哪些情况下

I'd like to also know in which scenarios are these two used.

推荐答案

你可能来问这个问题,因为你调用了一个方法来引发 InterruptedException

You've probably come to ask this question because you've called a method that throws InterruptedException.

首先,你应该看到 throws InterruptedException :方法签名的一部分,以及调用方法的可能结果。所以开始一个事实,一个 InterruptedException 是方法调用的完美有效的结果。

First of all, you should see throws InterruptedException for what it is: A part of the method signature and a possible outcome of calling the method you're calling. So start by embracing the fact that an InterruptedException is a perfectly valid result of the method call.

现在,如果你调用的方法会引发这样的异常,你的方法应该怎么做?你可以考虑以下几点:

Now, if the method you're calling throws such exception, what should your method do? You can figure out the answer by thinking about the following:

你正在实施的方法是否有意义 InterruptedException 换句话说,是一个 InterruptedException 在调用 方法?

Does it make sense for the method you are implementing to throw an InterruptedException? Put differently, is an InterruptedException a sensible outcome when calling your method?


  • 如果,那么 throws InterruptedException 应该是你的方法签名的一部分,你应该让异常传播(即根本不抓住它)。

  • If yes, then throws InterruptedException should be part of your method signature, and you should let the exception propagate (i.e. don't catch it at all).

示例:您的方法等待网络中的值完成计算并返回结果。如果阻止网络调用会引发 InterruptedException ,那么您的方法无法以正常方式完成计算。你会让 InterruptedException 传播。

Example: Your method waits for a value from the network to finish the computation and return a result. If the blocking network call throws an InterruptedException your method can not finish computation in a normal way. You let the InterruptedException propagate.

int computeSum(Server server) throws InterruptedException {
    // Any InterruptedException thrown below is propagated
    int a = server.getValueA();
    int b = server.getValueB();
    return a + b;
}



  • 如果 ,那么你不应该使用抛出InterruptedException 声明你的方法,你应该(必须!)捕获异常。在这种情况下,现在有两点很重要:

  • If no, then you should not declare your method with throws InterruptedException and you should (must!) catch the exception. Now two things are important to keep in mind in this situation:


    1. 有人中断了你的线程。有人可能急于取消操作,优雅地终止程序,或其他任何事情。你应该对那个人有礼貌,而不用多说,从你的方法回来。

    1. Someone interrupted your thread. That someone is probably eager to cancel the operation, terminate the program gracefully, or whatever. You should be polite to that someone and return from your method without further ado.

    即使你的方法可以管理在 InterruptedException 的情况下,明智的返回值线程已被中断的事实可能仍然很重要。特别地,调用您的方法的代码可能对执行方法是否发生中断感兴趣。因此,您应该记录事件中断,设置中断的标志: Thread.currentThread()。interrupt()

    Even though your method can manage to produce a sensible return value in case of an InterruptedException the fact that the thread has been interrupted may still be of importance. In particular, the code that calls your method may be interested in whether an interruption occurred during execution of your method. You should therefore log the fact an interruption took place by setting the interrupted flag: Thread.currentThread().interrupt()




    示例:用户要求打印两个值的总和。打印无法计算总和是可以接受的,如果无法计算总和(并且比使用<$ c $的堆栈跟踪使程序崩溃好得多) C> InterruptedException的)。换句话说,它不是有意义的是用声明这个方法抛出InterruptedException

    Example: The user has asked to print a the sum of two values. Printing "Failed to compute sum" is acceptable if the sum can't be computed (and much better than letting the program crash with a stack trace due to an InterruptedException). In other words, it does not make sense to declare this method with throws InterruptedException.

    void printSum(Server server) {
         try {
             int sum = computeSum(server);
             System.out.println("Sum: " + sum);
         } catch (InterruptedException e) {
             Thread.currentThread().interrupt();  // set interrupt flag
             System.out.println("Failed to compute sum");
         }
    }
    



  • 现在应该清楚的是,只要执行抛出新的RuntimeException(e)是一个坏主意。来电者不太礼貌您可以发明一个新的运行时异常,但根本原因(有人想要线程停止执行)可能会丢失。

    By now it should be clear that just doing throw new RuntimeException(e) is a bad idea. It isn't very polite to the caller. You could invent a new runtime exception but the root cause (someone wants the thread to stop execution) might get lost.

    其他示例: / p>

    Other examples:


    实施可运行 :正如您可能已经发现, Runnable.run 的签名不允许重新推出 InterruptedExceptions 。那么你 注册实施 Runnable ,这意味着你签署了可能的 InterruptedExceptions 。选择不同的界面,例如 可调用 ,或按照上述第二种方法。

    Implementing Runnable: As you may have discovered, the signature of Runnable.run does not allow for rethrowing InterruptedExceptions. Well, you signed up on implementing Runnable, which means that you signed up to deal with possible InterruptedExceptions. Either choose a different interface, such as Callable, or follow the second approach above.

    ;


    调用 Thread.sleep :你正在尝试读取一个文件,规范说你应该尝试10次,间隔1秒。你调用 Thread.sleep(1000)。所以,你需要处理 InterruptedException 。对于诸如 tryToReadFile 的方法来说,如果我被中断,我无法完成我尝试读取文件的操作 。换句话说,对于抛出 InterruptedExceptions 的方法是非常有意义的。

    Calling Thread.sleep: You're attempting read a file and the spec says you should try 10 times with 1 second in between. You call Thread.sleep(1000). So, you need to deal with InterruptedException. For a method such as tryToReadFile it makes perfect sense to say, "If I'm interrupted, I can't complete my action of trying to read the file". In other words, it makes perfect sense for the method to throw InterruptedExceptions.

    String tryToReadFile(File f) throws InterruptedException {
        for (int i = 0; i < 10; i++) {
            if (f.exists())
                return readFile(f);
            Thread.sleep(1000);
        }
        return null;
    }
    







    这篇文章已被重写为此处的文章。

    这篇关于处理Java中的InterruptedException的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

    查看全文
    登录 关闭
    扫码关注1秒登录
    发送“验证码”获取 | 15天全站免登陆