我的问题是关于InterruptedException,它是从Thread.sleep方法中抛出的。在合作时,ExecutorService我注意到一些我不理解的怪异行为;这是我的意思:
ExecutorService executor = Executors.newSingleThreadExecutor();
executor.submit(() -> {
while(true)
{
//DO SOMETHING
Thread.sleep(5000);
}
});
Run Code Online (Sandbox Code Playgroud)
有了这个代码,编译器不给我任何错误或消息InterruptedException从Thread.sleep应该被抓。但是,当我尝试更改循环条件并用诸如此类的变量替换“ true”时:
ExecutorService executor = Executors.newSingleThreadExecutor();
executor.submit(() -> {
while(tasksObserving)
{
//DO SOMETHING
Thread.sleep(5000);
}
});
Run Code Online (Sandbox Code Playgroud)
编译器不断抱怨InterruptedException必须处理。有人可以向我解释为什么会发生这种情况,为什么将条件设置为true则编译器会忽略InterruptedException?