Nuez
Nuez

Reputation: 25

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.

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. 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. I think I am implementing join() incorrectly, but I am unsure how to do it. I currently am doing it as

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

in my NewThread class. Any suggestions on how to get this working or a better way to go about it?

Upvotes: 0

Views: 232

Answers (2)

xtraclass
xtraclass

Reputation: 445

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.

Or 2nd way:

keep the method and call

     Thread.currentThread.join();

The rest looks fine.

Upvotes: 2

Peter Lawrey
Peter Lawrey

Reputation: 533930

You are implementins or overriding join to call itself endlessly

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.

You can use an ExecutorService

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

Upvotes: 5

Related Questions