0

I have a program with a swing GUI and I want to interrupt a thread when one of my JFrames is disposed of. Is there a quick way to do this? This is my first time working with concurrency.

MarcElrick
  • 93
  • 7

1 Answers1

1

Yes, you can do the following:

Create a JFrame subclass and override the dispose() method:

class MyFrame extends JFrame{
   private Thread otherThread;

   public MyFrame(Thread otherThread){
       super("MyFrame");

       this.otherThread=otherThread;
   }

   ...
   public void dispose(){
       otherThread.interrupt();
       super.dispose();
   }
}

However, please note that the usage of Thread.interrupt() is discouraged, because it is virtually impossible to control in which state a thread is interrupted.

Therefore, it is better to manually maintain an 'interrupted' flag for your own Thread (or Runnable) subclass and have the Thread stop its work as it sees fit.

For example:

class MyThread extends Thread{
   private boolean interrupted=false;


   public void interruptMyThread(){
       interrupted=true;
   }

   public void run(){
       while(true){
           // ... some work the thread does

           // ... a point in the thread where it's safe
           // to stop...
           if(interrupted){
               break;
           }
       }
   }
}

Then, instead of having a Thread reference in MyFrame, use a MyThread reference, and instead of calling otherThread.interrupt(), call otherThread.interruptMyThread().

So, the final MyFrame class would look something like:

class MyFrame extends JFrame{
   private MyThread otherThread;

   public MyFrame(MyThread otherThread){
       super("MyFrame");

       this.otherThread=otherThread;
   }

   ...
   public void dispose(){
       otherThread.interruptMyThread();
       super.dispose();
   }
}
Markus Fischer
  • 1,326
  • 8
  • 13