nulladex
nulladex

Reputation: 33

Multithreading - Wait for sub threads before creating a new thread - Java

I am creating "big threads", let's name them A, B, C... and put them in a queue. Each of these "big threads" are creating sub threads inside them. a1, a2, a3, b1, b2, b3, c1, c2, c3...

What I do is checking if A is TERMINATED and then starting the B and so on. But when A is finished a1, a2, a3 is starting and running simultaneously, and A becames TERMINATED. So B is starting right after with b1, b2, b3. I don't want this happen. How can I check or make A wait a1, a2, b3 and then be TERMINATED?

I've simplified and anonymized the code but the basic idea is the same:

Here is where runnable foo class is created and added to the queue FYI:

RunnableFooClass rc = new RunnableFooClass();
Thread t = new Thread(rc);

Here is run method of runnable bar class("sub thread") created inside runnable foo class ("big thread")

@Override
public void run() {
    for(int i=0; i<Constants.THREAD_NUM; i++){
         //initialize t
         t.start
    }
}

Following code is in an endless loop:

if(jobQueue.peek().getState() == Thread.State.TERMINATED){
    try {
        jobQueue.peek().join();
    } catch (InterruptedException e) {
        e.printStackTrace();
    }
    System.out.println(jobQueue.poll().getName() + "end.");
}
if(jobQueue.peek() != null){
    jobQueue.peek().start();
    System.out.println(jobQueue.peek().getName() + "start.");
}

Upvotes: 2

Views: 388

Answers (1)

noscreenname
noscreenname

Reputation: 3370

The basic solution is to use CountDownLatch.

In thread A create a latch initialized THREAD_NUM and pass it to each subthread:

@Override
public void run() {
    CountDownLatch latchA = new CountDownLatch(Constants.THREAD_NUM);
    for(int i=0; i<Constants.THREAD_NUM; i++){
         RunnableFooClass rc = new RunnableFooClass(latchA);
         Thread t = new Thread(rc);
         t.start();
    }
    latchA.await(); // wait for termination of all subthreads
}

Then, at the very end of the subthread's run()

latchA.countDown();

Upvotes: 2

Related Questions