Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

interrupt() doesn't work

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();
...
like image 926
Ori Popowski Avatar asked Dec 25 '11 00:12

Ori Popowski


1 Answers

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.

like image 51
Ted Hopp Avatar answered Sep 29 '22 20:09

Ted Hopp