java线程和主线程

什么是使主线程等到所有线程完成的最佳方法?

 for(int i = 0; i <n; i ++){
   线程t =新线程();
    t.start();

 }

 //等待所有线程完成

创建一个列表并等待所有。

 List threads = new ArrayList(); for(int i=0;i 

但是,使用ExecutorService可以更方便地处理线程池。

 ExecutorService es = Executors.newCachedThreadPool(); for(int i=0;i 
 List threads = new ArrayList(); for(int i=0;i 

它可以使用thread.join( ) ;来完成。

这里也已经回答了。 看一看。

  • Java – 等待多个线程完成。
  • Java – 如何等待所有线程完成?

示例:

 class MyThread implements Runnable { String name; // name of thread Thread t; MyThread(String threadname) { name = threadname; t = new Thread(this, name); System.out.println("New thread: " + t); t.start(); } public void run() { try { for (int i = 5; i > 0; i--) { System.out.println(name + ": " + i); Thread.sleep(1000); } } catch (InterruptedException e) { System.out.println(name + " interrupted."); } System.out.println(name + " exiting."); } } public class MainClass { public static void main(String args[]) { MyThread ob1 = new MyThread("One"); MyThread ob2 = new MyThread("Two"); MyThread ob3 = new MyThread("Three"); System.out.println("Thread One is alive: " + ob1.t.isAlive()); System.out.println("Thread Two is alive: " + ob2.t.isAlive()); System.out.println("Thread Three is alive: " + ob3.t.isAlive()); try { System.out.println("Waiting for threads to finish."); ob1.t.join(); ob2.t.join(); ob3.t.join(); } catch (InterruptedException e) { System.out.println("Main thread Interrupted"); } System.out.println("Thread One is alive: " + ob1.t.isAlive()); System.out.println("Thread Two is alive: " + ob2.t.isAlive()); System.out.println("Thread Three is alive: " + ob3.t.isAlive()); System.out.println("Main thread exiting."); } } 

虽然问题标记在“java”下,但也可以通过以下方式在C#中完成

  • C#:等待所有线程完成
  • 等待工作线程结束

我认为对于您的要求,最好的解决方案是CyclicBarrier查看http://download.oracle.com/javase/1.5.0/docs/api/java/util/concurrent/CyclicBarrier.html

要么

在这个例子

您可以使用CountDOwnLatch

 CountDownLatch lat = new CountDownLatch(noOfTasks); ExecutorService exec = Executors.newFixedThreadPool(4); while(...) { exec.execute(new MyTask()); } try { lat.await(); } catch (InterruptedException E) { // } 

并在你的任务中(包含在try / finally中)

 lat.countDown();