完成所有线程后打印数据

use*_*810 2 java multithreading

我想在我创建的2个线程完成运行方法之后才打印数组.我怎么能这样做?

Eng*_*uad 6

看看这个方法Thread#join().例如:

Thread a = ...;
a.start();
a.join(); // wait until Thread a finishes
Run Code Online (Sandbox Code Playgroud)


Ama*_*mar 6

简单的。使用Thread.join()。当您生成线程时,将它们添加到列表中并遍历该列表并调用 thread.join()。一旦您退出该循环,您的所有线程都被确认已完成。然后您可以在此之后使用打印语句。

像这样的东西:

import java.lang.*;

public class ThreadDemo implements Runnable {

   public void run() {

      //some implementation here
   }

   public static void main(String args[]) throws Exception {

      List<Thread> threadList = new ArrayList<Thread>();
      Thread t1 = new Thread(new ThreadDemo());
      t1.start();
      threadList.add(t1);
      Thread t2 = new Thread(new ThreadDemo());
      t2.start();
      threadList.add(t2);
      for(Thread t : threadList) {
          // waits for this thread to die
          t.join();
      }
      System.out.print("All the threads are completed by now");
   }
}
Run Code Online (Sandbox Code Playgroud)