Java的Thread.sleep什么时候抛出InterruptedException? [英] When does Java's Thread.sleep throw InterruptedException?

查看:1571
本文介绍了Java的Thread.sleep什么时候抛出InterruptedException?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Java的Thread.sleep什么时候抛出InterruptedException?忽视它是否安全?我没有做任何多线程。我只想等待几秒钟才重试某些操作。

When does Java's Thread.sleep throw InterruptedException? Is it safe to ignore it? I am not doing any multithreading. I just want to wait for a few seconds before retrying some operation.

推荐答案

通常不应忽略该异常。请看下面的论文:

You should generally NOT ignore the exception. Take a look at the following paper:


不要吞下中断

有时抛出InterruptedException是
不是一个选项,例如当Runnable定义的任务调用
可中断方法时。在这种情况下,你不能重新抛出
InterruptedException,但你也不想做任何事情。当
阻塞方法检测到中断并抛出InterruptedException时,
清除中断状态。如果你捕获InterruptedException
但不能重新抛出它,你应该保留
中断发生的证据,以便调用堆栈上的代码可以
了解中断并在需要时响应它至。这个任务
是通过调用interrupt()来重新中断当前的
线程来完成的,如清单3所示。至少,每当你捕获
InterruptedException并且不重新抛出它时,在返回之前重新中断当前的
线程。

Sometimes throwing InterruptedException is not an option, such as when a task defined by Runnable calls an interruptible method. In this case, you can't rethrow InterruptedException, but you also do not want to do nothing. When a blocking method detects interruption and throws InterruptedException, it clears the interrupted status. 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. At the very least, whenever you catch InterruptedException and don't rethrow it, reinterrupt the current thread before returning.

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



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