java线程和主线程

时间:2011-02-21 12:49:24

标签: java multithreading

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

for(int i=0;i<n;i++){
   Thread t=new Thread();
   t.start();

}

//wait for all threads to finish

5 个答案:

答案 0 :(得分:18)

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

List<Thread> threads = new ArrayList<Thread>();
for(int i=0;i<n;i++){
    Thread t=new Thread();
    t.start();
    threads.add(t);
}

for(Thread t: threads) t.join();

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

ExecutorService es = Executors.newCachedThreadPool();
for(int i=0;i<n;i++)
   es.submit(new Task(n));
es.shutdown();
es.awaitTermination(timeout, TimeUnit.SECONDS);

答案 1 :(得分:3)

List<Thread> threads = new ArrayList<Thread>();

for(int i=0;i<n;i++){
   Thread t=new Thread();
   threads.add(t);
   t.start();

}


for(Thread t:threads){
t.join();
}

答案 2 :(得分:1)

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

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

示例:

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#中完成

答案 3 :(得分:0)

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

at this example

答案 4 :(得分:0)

您可以使用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();