Jayyrus
Jayyrus

Reputation: 13051

How to stop, pause, cancel a thread in java

i'm developing an app in java that launches some threads that do some jobs and update a JTable with a JProgressBar. I develope a JPopupMenu on the JTable that has some JMenuItem:

So i want to be able to do it.

When user add new thread in JTable i save the thread in a ArrayList<Thread>, so i have to implement

stop.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent ae) {

            }
        });

and the other..

so i try , with the hypothesis that i have the index of current thread:

Thread t = working.get(selectedThread); //where working is my `ArrayList<Thread>`
t.interrupt();

but nothing.. it continue working... so i try:

try {
                        working.get(actualRow).wait();
                    } catch (InterruptedException ex) {
                        Logger.getLogger(PannelloRicerca.class.getName()).log(Level.SEVERE, null, ex);
                    }

but it get me IllegalStateMonitorException on wait(), so i don't know how to do.. can someone help me?

Upvotes: 3

Views: 1769

Answers (2)

SJuan76
SJuan76

Reputation: 24885

The IllegalStateMonitorException is because a thread can only wait in an object it it 'owns' (I don't remember if it is the right term) it.

You need to synchronize by the same object first, in order to ensure that nobody else is already waiting on this object.

 synchronize (working.get(actualRow)) {
   working.get(actualRow).wait(); 
 }

Upvotes: 1

Gray
Gray

Reputation: 116878

The Thread.interrupt() call only sets the interrupt bit on the Thread and it causes any wait or sleep calls to throw InterruptedException. It does not cancel the execution of the thread like many expect.

You can test for the interrupt bit in a thread like this:

while (!Thread.currentThread().isInterrupted()) {
   ...
}

A typical way for folks to stop a thread is to have an AtomicBoolean (or volatile boolean) and do something like:

AtomicBoolean running = new AtomicBoolean(true);
while (running.set()) {
    ...
}

...
// then in the other thread (like the main thread) you stop the thread by:
runner.set(false);

You are getting the IllegalStateMonitorException because you are calling wait without being inside of a synchronized block for the object you are waiting on. You need to do something like:

Thread t = working.get(actualRow);
synchronized (t) {
    t.wait();
}

Although I'm not sure that's what you want. Maybe you want to join on the thread which waits for it to finish?

   working.get(actualRow).join();

Upvotes: 2

Related Questions