本文介绍了同步两个线程的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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.

这篇关于同步两个线程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

06-26 08:07