How to know when two Threads ended up in Swing?

Asked

Viewed 329 times

2

I have a method that performs two tasks. I would like two threads perform each task. Tasks do not share data, are completely independent.

Before starting the tasks is shown a dialog with the information "Wait, processing...".

Here are the codes:

final JDialog dialog = new JDialog(this, true);
SwingWorker<Void, Void> worker = new SwingWorker<Void, Void>() {
   @Override
   protected Void doInBackground() throws Exception {
      // Faz trabalho
      return null;
   }
   @Override
   protected void done() {
      // Devo fechar Dialog? O outro terminou?
   }
};

SwingWorker<Void, Void> worker2 = new SwingWorker<Void, Void>() {
   @Override
   protected Void doInBackground() throws Exception {
      // Faz trabalho
      return null;
   }
   @Override
   protected void done() {
      //Devo fechar Dialog? O outro terminou?
   }
};

worker.execute();
worker2.execute();
dialog.setVisible(true);
// Devo fechar o dialog aqui?

The questions are already commented on in the code.

I would like to close the dialog only when both threads finished. How to know when they finished? Who should close the dialog?

  • 1

    That’s easy, that’s when a third thread comes into play! /s

2 answers

4


  • Create a CountDownLatch started in 2;
  • Create both SwingWorkers, passing to each one the CountDownLatch as a reference. In the done() of each call the countDown() of latch. Do it in the methods done(), since they will be called regardless of how the method doInBackground() end (in case of launching a Exception);
  • Create a third SwingWorker, passing as reference the CountDownLatch. In this worker call the method await() of latch in the doInBackground(). In the method done() that SwingWorker can close the dialog safely.

Source: https://stackoverflow.com/questions/26554386/how-to-know-when-two-threads-are-finished-in-swing

1

So, I don’t know if this is the best solution because I don’t move a lot with swing.

But you need to wait for both "thread" to finish to warn the dialog.

   while( true ){
     if( worker.isDone() && worker2.isDone() )
     {
        dialog.setVisible(true);
        break;
     }
   }

Putting this after:

worker.execute();
worker2.execute();

It should work, but like I said, I’m not sure that’s the best solution. I hope I’ve helped.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.