同步两个线程

问题描述:

我有两个线程,我希望第二个线程等待第一个线程完成.我怎样才能做到这一点?

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

这是我的代码:

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

使用 Thread.join() 方法.从第二个线程,调用

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

firstThread.join();

有一些可选的重载也需要超时.您需要处理 InterruptedException,以防您的第二个线程在第一个线程完成之前中断.

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.