Mauro
Mauro

Reputation: 11

Java thread join()

If I have one array of 10 thread ready "to be used" and if I have something like

for (int i=0;i< MyThreadArray.length: i++){
MyThreadArray[i].start()
MyThreadArray.join()
}

If the thread #6 has a sleep() of 5 minutes, how can I run the thread #7 before the end of the #6? I have to wait for the end of the #6 or there is some instructions to run the "next thread"?

Upvotes: 1

Views: 186

Answers (1)

Fureeish
Fureeish

Reputation: 13434

Use two loops. In the first one you should start all threads:

for (int i=0;i< MyThreadArray.length: i++){
    MyThreadArray[i].start()
}

This will start all of them. Afterwards, you want to wait for them to finish:

for (int i=0;i< MyThreadArray.length: i++){
    MyThreadArray[i].join()
    // notice    ^^^ you had a typo there
}

This will wait for each thread to finish before moving on.

Also, do note that this particular logic:

for (int i=0;i< MyThreadArray.length: i++){
    MyThreadArray[i].start()
    MyThreadArray[i].join()
}

is simply a worse version of not using parallelism, since it will wait for every single thread sequentially, additionally adding some overhead of starting a Thread.

Upvotes: 4

Related Questions