interrupt() doesn't work

为君一笑 提交于 2019-11-30 03:31:00

问题


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();
}

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?

Edit:

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();
...

回答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.




回答2:


You are probably calling cancel on the wrong thread. If you look at it, it cancel() cancels this thread. You probably want to cancel some other thread.

It is also true that your call to isInterrupted() is unnecessary, but that won't cause interrupts to be lost ...


On the other hand, if the cancel method is a method of a class that extends Thread, then the this could be the thread that needs cancelling. (The problem for us folks trying to answer is that there is/was insufficient detail in the original question ...)



来源:https://stackoverflow.com/questions/8627719/interrupt-doesnt-work

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!