traveh
traveh

Reputation: 2884

Join multiple threads with timeout

I need to join multiple threads with a timeout. Something like Thread.join(long millis) but for multiple threads.

I found some posts about joining multiple threads, but not regarding joining with timeout.

The code I'm changing is:

for (Thread thread : threads) {
    thread.join(units.toMillis(timeout));
}

But this obviously waits for each thread separately having the effect of waiting up to threads.length * timeout. I want to wait up to timeout for all threads altogether.

What would be the right way to do this?

Upvotes: 5

Views: 799

Answers (2)

Pavel Niedoba
Pavel Niedoba

Reputation: 1577

you can track elapsed time and join on timeout - elapsed, if it's negative, you don't need to wait at all, it's time-outed already

Upvotes: 0

George
George

Reputation: 915

Sounds like you're trying to implement a barrier with a timeout. Have you tried this: http://docs.oracle.com/javase/7/docs/api/java/util/concurrent/CyclicBarrier.html

Upvotes: 1

Related Questions