中断Java中的循环线程
我正在尝试了解线程在 Java 中的工作原理,目前正在研究如何实现可以取消的循环线程。代码如下:
public static void main(String[] args) throws Exception {
Thread t = new Thread() {
@Override
public void run() {
System.out.println("THREAD: started");
try {
while(!isInterrupted()) {
System.out.printf("THREAD: working...\n");
Thread.sleep(100);
}
} catch(InterruptedException e) {
// we're interrupted on Thread.sleep(), ok
// EDIT
interrupt();
} finally {
// we've either finished normally
// or got an InterruptedException on call to Thread.sleep()
// or finished because of isInterrupted() flag
// clean-up and we're done
System.out.println("THREAD: done");
}
}
};
t.start();
Thread.sleep(500);
System.out.println("CALLER: asking to stop");
t.interrupt();
t.join();
System.out.println("CALLER: thread finished");
}
我创建的线程预计迟早会被中断。因此,我检查 isInterrupted() 标志来决定是否需要继续,并捕获 InterruptedException
来处理我处于等待操作(sleep
, 加入
,等待
)。
我想澄清的是:
- 这种任务使用中断机制可以吗? (与拥有
易失性布尔值shouldStop
相比) - 这个解决方案正确吗?
- 我吞下InterruptedException正常吗?我不太感兴趣有人要求我的线程中断的代码段是什么。
- 有没有更短的方法来解决这个问题? (要点是具有“无限”循环)
编辑 在 catch 中为 InterruptedException
添加了对 interrupt()
的调用。
I'm trying to understand how threads work in Java and currently investigating how to implement looped threads that can be cancelled. Here's the code:
public static void main(String[] args) throws Exception {
Thread t = new Thread() {
@Override
public void run() {
System.out.println("THREAD: started");
try {
while(!isInterrupted()) {
System.out.printf("THREAD: working...\n");
Thread.sleep(100);
}
} catch(InterruptedException e) {
// we're interrupted on Thread.sleep(), ok
// EDIT
interrupt();
} finally {
// we've either finished normally
// or got an InterruptedException on call to Thread.sleep()
// or finished because of isInterrupted() flag
// clean-up and we're done
System.out.println("THREAD: done");
}
}
};
t.start();
Thread.sleep(500);
System.out.println("CALLER: asking to stop");
t.interrupt();
t.join();
System.out.println("CALLER: thread finished");
}
The thread I create is indended to be interrupted sooner or later. So, I check isInterrupted() flag to decide whether I need to go on and also catch InterruptedException
to handle cases when I'm in a kind of waiting operation (sleep
, join
, wait
).
Things I'd like to clarify are:
- Is it fine to use interruption mechanism for this kind of task? (comparing to having
volatile boolean shouldStop
) - Is this solution correct?
- Is it normal that I swallow InterruptedException? I'm not really interested what was the piece of code where someone asked my thread to interrupt.
- Are there any shorter ways to solve this problem? (the main point is having 'infinite' loop)
EDIT
Added call to interrupt()
in catch for InterruptedException
.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
我的回答是“不”。 3:
基本上问题是:中断异常有什么目的?它告诉你停止阻塞(例如睡觉)并早点返回。
有两种方法处理 InterruptedException:
简单地吞下 InterruptedException 并不是一个好主意,因为这种中断的目的是最终终止。但您只会被要求打断,以便您还有时间进行清理。
在这种情况下,这可能是我自己的“过度反应”,但通常此类代码要复杂得多,您怎么知道该线程中的某些后续代码不会再次调用阻塞方法?
编辑
否则我认为你所做的很好。不过,对我来说有点令人惊讶,因为我从未见过有人在自己的代码中真正这样做过。
可以在这里找到解释原因的有趣文章: http://www .ibm.com/developerworks/java/library/j-jtp05236/index.html
I am answering no. 3:
Basically the question is: What purpose does an Interrupted exception have? It tells you to stop blocking (e.g. sleeping) and return early.
There are two ways dealing with an InterruptedException:
Thread.currentThread.interrupt()
again and do your cleanup work. This way you can be sure that another method in your thread starting to sleep will throw againSimply swallowing an
InterruptedException
is not a good idea regarding the purpose of such an interrupt which is to finally terminate. But you are only asked to interrupt so you still have time to clean up.In this case this might be an 'overreaction' of myself, but typically such code is much more complicated and how do you know, that some follow-up-code in this Thread would not call a blocking method again?
EDIT
Otherwise I think what you're doing is fine. For me a bit surprising, though, because I never saw anyone in his own code actually doing it.
And interesting article explaining why can be found here: http://www.ibm.com/developerworks/java/library/j-jtp05236/index.html
Thread.currentThread().interrupt();
Thread.currentThread().interrupt();
1)根据Java Concurrency in Practice一书,您的示例中的方式优于使用易失性标志(这是多余的,因为您已经有了中断标志)。这就是 InterruptedExceptions 的用途。
2)是的
3)只要恢复中断标志状态就可以吃掉异常。该异常并不代表错误,因此吃掉它不会丢失任何信息,它纯粹是一种转移控制的手段。 (恢复中断标志状态对于您有嵌套控制结构的情况非常重要,每个控制结构都需要被告知线程正在取消,对于像您这样的简单示例来说,这是很好的形式,但如果它丢失了,也不会造成任何损害。)
4 ) 不
1) The way in your example is preferable to using a volatile flag (which is redundant since you already have the interrupted flag), according to the Java Concurrency in Practice book. It is how InterruptedExceptions were intended to be used.
2) Yes
3) you can eat the exception as long as you restore the interrupt flag status. The exception doesn't represent an error so eating it doesn't lose any information, it is purely a means of transferring control. (Restoring the interrupt flag status is important for cases where you have nested control structures that each need to be informed that the thread is cancelling, for a simple example like yours it's good form but if it's missing it won't hurt anything.)
4) no
使用中断很好,但要用好它们。您必须在 catch 中重新抛出 Thread.currentThread().interrupt() 。下面是一段代码,说明了原因:
另一件事是,在等待
InputStreams
时,中断
并不总是起作用。然后,您可以使用(对于某些)InterruptedIOException
,但它并不总是有效。要了解这些情况,您可能想尝试这段代码:It's fine to use Interruption, but use them well. You have to re-throw
Thread.currentThread().interrupt()
in your catch. Here is a piece of code showing why :Another thing is,
Interruptions
don't always work when waiting onInputStreams
. You then can use (for some)InterruptedIOException
, but it won't always work. To understand these cases, you might want to try this piece of code :