简体   繁体   English

如何在Java中启动更多线程之前等待线程完成

[英]How to wait for a thread to finish before starting more in Java

So say that I have 10 things to run, but I can only have 3 threads running at a time. 这么说吧,我有10件事要运行,但是一次只能运行3个线程。

ArrayList<NewThread> threads = new ArrayList<NewThread>();

for(int i = 1; i < args.length; i++) {
   NewThread t = new NewThread(args[i]);
   threads.add(newThread);

   if( (i%3) == 0) {
      for (NewThread nt : threads) {
         nt.join();
      }
      threads.clear();
   }
}

The class NewThreads implements Runnable. NewThreads类实现Runnable。 I thought the join() method would work to make it wait for the threads to finish before looping around again and kicking off the next batch of threads, but instead I get a stack overflow exception. 我认为join()方法可以使它等待线程完成,然后再次循环并开始下一批线程,但是我却得到了堆栈溢出异常。 I think I am implementing join() incorrectly, but I am unsure how to do it. 我想我执行的join()错误,但是我不确定该怎么做。 I currently am doing it as 我目前正在这样做

public void join() {
   this.join();
}

in my NewThread class. 在我的NewThread类中。 Any suggestions on how to get this working or a better way to go about it? 关于如何使它工作或有更好的解决方法的任何建议?

You are implementins or overriding join to call itself endlessly 您是Implementins或重载join来不断调用自己

public void join() {
   this.join(); // call myself until I blow up.
}

The simplest solution is to use Thread.join() already there, but a better solution is to use a fixed size thread pool so you don't have to start and stop threads which can waste a lot of time and code. 最简单的解决方案是使用已经存在的Thread.join(),但更好的解决方案是使用固定大小的线程池,因此您不必启动和停止线程,这会浪费大量时间和代码。

You can use an ExecutorService 您可以使用ExecutorService

ExecutorService es = Executors.newFixedThreadPool(3);
for(int i=0;i<10;i++)
    es.submit(new Task(i));

This is just a simple mistake. 这只是一个简单的错误。

Remove the method 删除方法

    public void join() {
      this.join();
    }

This method calls itself again and again. 此方法一次又一次地调用自身。 NewThread should extend Thread. NewThread应该扩展Thread。

Or 2nd way: 或第二种方式:

keep the method and call 保留方法并调用

     Thread.currentThread.join();

The rest looks fine. 其余的看起来不错。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM