4

我想打电话Thread.sleep,并传播InterruptExceptionif 确实它被抛出了。

虚构语法:

Interruptibles.sleep(1000);

这相当于

try {
    Thread.sleep(1000);
} catch (InterruptException e) {
    throw Throwables.propagate(e);
}

公共库(番石榴、apache commons 等)中是否有类似的功能。

4

2 回答 2

9

包装在 RuntimeException 中可能会导致痛苦。这是一个复杂的话题,我推荐 Java Concurrency in Practice 中的相关部分,以充分了解您的选择。
Guava 有sleepUninterruptibly,它实现了那里描述的标准习语之一。

于 2013-01-01T04:06:00.767 回答
3

你可以这样做。

try {
    Thread.sleep(1000);
} catch (InterruptException e) {
    Thread.currentThread().interrupt();
}

或者

try {
    Thread.sleep(1000);
} catch (InterruptException e) {
    Thread.currentThread().stop(e);
}

但通常最好让异常“冒泡”到可以正确处理的地方。您的 IDE 可以通过填写您需要的代码来简化此操作。

于 2012-12-31T15:25:32.933 回答