interrupt()不工作 [英] interrupt() doesn't work

查看:156
本文介绍了interrupt()不工作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图在以下代码中终止该线程:

I am trying to terminate the thread in the following code:

public synchronized void run() {
    try {
        while (!Thread.currentThread().isInterrupted()) {
            this.scan();
            this.distribute();
            this.wait();
        }
    } catch (InterruptedException e) {}
}

public void cancel() {
    this.interrupt();
}

但是线程不会终止。我使用调试器,发现在命令 this.interrupt()后,线程不会中断(我把一个监视表达式 this.isInterrupted(),它保持 false )。任何人都知道为什么这个主题不会中断?

But the thread won't terminate. I used the debugger and found out that after the command this.interrupt(), the thread doesn't get interrupted (I put a watch on the expression this.isInterrupted() and it stays false). Anyone has an idea why this thread won't get interrupted?

。原来有这个线程的两个实例。我附加有问题的代码,导致这:

The problem has been found. Turns out that there were two instances of this thread. I am attaching the problematic code that lead to this:

/* (class Detector extends Thread) */
Detector detector = new Detector(board);
...
Thread tdetector  = new Thread(detector); /* WRONG!!! */
...
tdetector.start();
...


推荐答案

href =http://docs.oracle.com/javase/6/docs/api/java/lang/Thread.html#interrupt%28%29 =nofollow>文档,如果您当线程处于 wait()状态时,调用 interrupt(),中断标志不会置1。

According to the docs, if you call interrupt() while the thread is in a wait() state, the interrupt flag will not be set. You should be getting an interrupted exception, which will exit the loop (and the thread).

EDIT

根据我的评论和你的回答,问题是你有多个这样的线程运行。

Per my comment and your response, the problem is that you have more than one of these threads running.

这篇关于interrupt()不工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆