我不断从线程内的线程收到中断,它不会让我因此而破坏主线程。我仍然想使用 Thread.sleep() 来减慢循环速度。
主线程:
startEngine.setOnAction((ActionEvent e) -> {
executor.submit(new Runnable() {
@Override
public void run() {
while (!Thread.currentThread().isInterrupted()) {
lifeInstance.runEngine();
}
}
});
});
stopEngine.setOnAction((ActionEvent e) -> {
executor.shutdownNow();
});
executor.submit 正在调用 lifeInstance.runEngine(),即:
public void runEngine() {
//logic...
try {
Thread.sleep(1000);
} catch (InterruptedException ex) {
Logger.getLogger(LifeEngine.class.getName()).log(Level.SEVERE, null, ex);
return;
}
}
错误:
//从 runEngine() 打印出内容
Nov 06, 2016 6:04:52 PM thecell.LifeEngine runEngine
SEVERE: null
java.lang.InterruptedException: sleep interrupted
at java.lang.Thread.sleep(Native Method)
at thecell.LifeEngine.runEngine(LifeEngine.java:66)
at UIControls.RightControls$1.run(RightControls.java:48)
at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:511)
at java.util.concurrent.FutureTask.run(FutureTask.java:266)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
at java.lang.Thread.run(Thread.java:745)
//不断从 runEngine() 中打印出内容
最佳答案
因为当 runEngine()
方法在 InterruptedException
上返回时,isInterrupted()
返回 false
。
摘自《Java并发实践》一书:
Blocking library methods like
Thread.sleep
andObject.wait
try to detect when a thread has been interrupted and return early. They respond to interruption by clearing the interrupted status and throwing InterruptedException, indicating that the blocking operation completed early due to interruption.
当你得到异常时,中断状态被清除。您可以在返回前重置它:
} catch (InterruptedException ex) {
Logger.getLogger(LifeEngine.class.getName()).log(Level.SEVERE, null, ex);
Thread.currentThread().interrupt();
return;
}
实际上,您应该这样做,因为您的任务代码是由线程池执行的,并且在任务代码处理完中断状态后保留中断状态是一个很好的行为。这样线程池也能响应中断。
关于java - 当另一个线程终止时终止 Thread.Sleep() ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40456028/