java java线程和主线程

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5066160/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-30 09:15:19  来源:igfitidea点击:

java threads and main thread

javamultithreading

提问by user121196

what's the best way to make main thread to wait until all threads are finished?

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

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

}

//wait for all threads to finish

回答by Peter Lawrey

Create a list and wait for the all.

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

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();

However using an ExecutorService can be a more elegant way to handle a pool of threads.

然而,使用 ExecutorService 可以是处理线程池的更优雅的方式。

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

回答by Jigar Joshi

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();
}

回答by sgokhales

It can be done using thread.join( );.

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

It is also answered here already. Have a look.

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

Example :

例子 :

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


Although the question is tagged under "java", it can be also done in C# in following ways

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

回答by FatherMathew

You can use a CountDOwnLatch

您可以使用CountDOwnLatch

CountDownLatch lat = new CountDownLatch(noOfTasks);

ExecutorService exec = Executors.newFixedThreadPool(4);

while(...) {

  exec.execute(new MyTask());

}


try {

  lat.await();

} 
catch (InterruptedException E) {

 //

}

and within your task (enclose in try / finally)

并在您的任务中(附在 try / finally 中)

lat.countDown();

回答by carmen_munich

I think for your requirement the best solution is the CyclicBarrierlook at http://download.oracle.com/javase/1.5.0/docs/api/java/util/concurrent/CyclicBarrier.html

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

or

或者

at this example

在这个例子中