Synchronizing two streams

I have two threads and I want the second thread to wait for the first thread to finish. How can i do this?

This code of mine:

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

      

+1


a source to share


5 answers


Use the method Thread.join()

. From the second thread, call

firstThread.join();

      



There are additional overloads that also require timeouts. You will need to handle InterruptedException

if your second thread is interrupted before the first thread completes.

+9


a source


You need to call:

first_thread.join();

      



from the second stream.

See Thread.join documentation .

+4


a source


Just to cover all the basics, you can use semaphores as well.

At the waiter

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

      

The waitee

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

      

This approach is by no means perfect if the waitee just ceases to exist, but semaphores are interesting, so I think it was important.

+1


a source


If your first thread is not doing something useful at the same time as the second thread, you might be better off with one thread. If they both do something useful, then use join () as suggested.

0


a source


You might also consider using the java.util.concurrent package . CountDownLatch or CyclicBarrier can be used to coordinate threads, while slaves are good for managing concurrent tasks.

0


a source







All Articles