问题
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..");
}
}
回答1:
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.
回答2:
You need to call:
first_thread.join();
from the second thread.
See the Thread.join documentation.
回答3:
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.
回答4:
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.
回答5:
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.
来源:https://stackoverflow.com/questions/873237/synchronizing-two-threads