【发布时间】:2015-05-22 10:20:56
【问题描述】:
假设我有以下代码:
public void run(){
while (true){
function1();
...
functionN();
}
}
我想“优雅地”退出 - 这对我来说意味着一旦我发送了一个关闭信号并且当前线程处于 functionK(),该线程将“打破”循环并退出运行。
所以我尝试像这样使用 Thread.interrupt():
public void run(){
while (true){
try {
function1();
...
functionN();
} catch (InterruptedException ex) {
/* Cleanup and exit. */
}
}
}
但这不起作用 - 即使打开中断标志,线程也会继续无休止地运行。
仅作记录:
public void run(){
while (!thread.isInterrupted()){
try {
function1();
...
functionN();
} catch (InterruptedException ex) {
/* Cleanup and exit. */
}
}
}
停止循环,但对我没有帮助。由于每个函数执行的操作可能需要几分钟,并且有很多不同的函数,因此在每个函数之前检查中断标志是否为一个可能会很昂贵(特别是因为大多数情况下应用程序运行顺利)。
我想知道是否有一种特殊的机制可以用来解决这类问题。
【问题讨论】:
-
如果有多个线程,那么它是可能的!使用同步。
-
这段代码只有一个线程工作。
标签: java multithreading concurrency