0

I need to interrupt swingworkers, but if the thread is running some fragment, it should interrupt after that. Something like this:

public class worker extends SwingWorker<Integer, String>{
    //(...) constructors and everything else

    protected Integer doInBackground() throws Exception{
        //Code that can be interrupted
        while(true){
            //(...) more code that can be interrupted

            //This shouldn't be interrupted, has to wait till the loop ends
            for(int i=0; i<10; i++){ 

            //(...) more code that can be interrupted
        }            
    }
}

Interrupting the worker with:

Worker worker = new Worker();
worker.execute();
worker.cancel(true);

I've tried synchronized blocks, but not sure if that doesn't work or i'm just doing it wrong.

Is there a way? Thanks!

Hans Araya
  • 345
  • 2
  • 15
  • As noted in [this answer](https://stackoverflow.com/a/671053/4756299), you don't interrupt a thread. You end the thread in a controlled manner. – Andrew Henle Jun 06 '17 at 12:55

1 Answers1

0

Any way you can control either by a flag which will check the thread periodically. So before start you can check the flag or interrupt then Proceed.

make flag as volatile so it will be visible to all thread or AtomicBoolean

 while (flag) {
       //do stuff here
     }

or you can use interrupt to cancel the task.

 try {
      while(!Thread.currentThread().isInterrupted()) {
         // ...
      }
   } catch (InterruptedException consumed)

   }
gati sahu
  • 2,576
  • 2
  • 10
  • 16