MOUZA
MOUZA

Reputation:

Synchronizing two threads

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..");
  }
}

Upvotes: 1

Views: 1088

Answers (5)

stili
stili

Reputation: 674

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.

Upvotes: 0

Alex Gartrell
Alex Gartrell

Reputation: 2564

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.

Upvotes: 1

Peter Lawrey
Peter Lawrey

Reputation: 533890

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.

Upvotes: 0

RichieHindle
RichieHindle

Reputation: 281875

You need to call:

first_thread.join();

from the second thread.

See the Thread.join documentation.

Upvotes: 4

Jon Skeet
Jon Skeet

Reputation: 1504062

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.

Upvotes: 9

Related Questions