How to know when two threads have ended in Swing?

2

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

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

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?

Questions are already commented out in the code.

I would like to close dialog only when the two threads are over. How do you know when they are over? Who should close dialog ?

    
asked by anonymous 24.10.2014 / 20:21

2 answers

4
  • Create a CountDownLatch started in 2;
  • Create the two SwingWorkers , passing each CountDownLatch as a reference. In the done() methods of each call the countDown() of latch . Do this in the done() methods, since they will be called regardless of how the doInBackground() method ends (in case you cast a Exception );
  • Create a third SwingWorker , passing as CountDownLatch . In this worker call method await() of latch in doInBackground() . In the done() method of this SwingWorker you can safely close dialog .

Source: link

    
27.10.2014 / 10:59
1

So, I do not know if this is the best solution because I do not get too much swing.

But you have to wait for the two "threads" to finish telling the dialog.

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

Placing this after:

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

It should work, but as I said, I'm not sure if this is the best solution. I hope I have helped.

    
24.10.2014 / 20:55