Ale*_*tin 1 java multithreading exception
很长一段时间我一直在使用以下函数使当前线程休眠一段时间:
class Utils {
static public sleep(int ms) {
try {
Thread.sleep(ms);
} catch(InterruptedException x) {}
}
}
Run Code Online (Sandbox Code Playgroud)
但是,因为我很容易忽略异常,我想知道是否会出现这种情况会变成邪恶的情况?
如果你没有在你自己的代码中使用中断,你应该保持中断状态:
catch(InterruptedException x) {
Thread.currentThread.interrupt();
}
Run Code Online (Sandbox Code Playgroud)
或者你可以通过投掷来处理它InterruptedException.这会立即让调用者知道有中断,否则稍后可以使用isInterrupted()进行检查.
如果您必须全天休眠,那么您可以在中断后继续休眠,然后重新中断线程.请参阅guava的Uninterruptibles.sleepUninterruptibly实现.
通过不清除线程的中断状态,您将阻止您的代码干扰可能正在使用中断的任何其他内容.因此,如果将来你想要中断一个线程,你就不会有一些模糊的错误,有时它会起作用,有时则不会.
如果你永远不会使用中断,它可能会完全忽略它,但保持灵活性以防万一.