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..");
}
}
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.
a source to share
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.
a source to share
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.
a source to share