Reputation: 10672
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?
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();
...
Upvotes: 8
Views: 2844
Reputation: 234857
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.
Upvotes: 5
Reputation: 719661
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 ...)
Upvotes: 2