views:

296

answers:

5

I have two threads and I want the second thread to wait until first thread finishes. How can I accomplish this?

This my code:

public class NewClass1 implements Runnable {

    // in main
    CallMatlab c = new CallMatlab();
    CUI m = new CUI();
    Thread t1 = new Thread(c);
    t1.start();
    Thread t2 = new Thread(m);
    try {
      t1.join();
    } catch (InterruptedException ex) { 
      Logger.getLogger(NewClass1.class.getName()).log(Level.SEVERE, null, ex);
    }
    t2.start();

  //
  public void run() {
    throw new UnsupportedOperationException("Not su..");
  }
}
+8  A: 

Use the Thread.join() method. From the second thread, call

firstThread.join();

There are optional overloads which take timeouts, too. You'll need to handle InterruptedException in case your second thread is interrupted before the first thread completes.

Jon Skeet
+4  A: 

You need to call:

first_thread.join();

from the second thread.

See the Thread.join documentation.

RichieHindle
A: 

Unless your first thread is doing something useful at the same time as the second thread, you may be better off with one thread. If they are both doing something useful, use join() as has been suggested.

Peter Lawrey
this my codepublic class NewClass1 implements Runnable { in main CallMatlab c = new CallMatlab(); CUI m = new CUI(); Thread t1 = new Thread(c); t1.start(); Thread t2 = new Thread(m); try { t1.join(); } catch (InterruptedException ex) { Logger.getLogger(NewClass1.class.getName()).log(Level.SEVERE, null, ex); } t2.start(); public void run() { throw new UnsupportedOperationException("Not su..");
+1  A: 

Just for the sake of covering all basics, you could also use semaphores.

In the waiter

/* spawn thread */
/* Do interesting stuff */
sem.acquire();

In the waitee

/* wake up in the world */
/* do intersting stuff */
sem.release();

This approach is in no way superior if the waitee is just going to terminate, but semaphores are interesting, so I think it was worth stating.

Alex Gartrell
A: 

You may also consider using the java.util.concurrent package. CountDownLatch or CyclicBarrier can be used for coordinating threads, while Executors are nice for managing concurrent tasks.

stili