Assume I have a main thead. In this main thread I create and start 5 threads. Then my main thread has to wait until one of those previous created threads has finished. When such a thread is finished, my main thread has to create and start another thread, so that there are always 5 (or less) threads alive. So, my question is: Is there something like CountDownLatch that enables me wait when an upper threshold has been reached?
Asked
Active
Viewed 151 times
-3
-
Does the main thread have to do this? Just add a callback/listener to your runnables. – Sotirios Delimanolis Dec 16 '14 at 18:22
-
2possible duplicate of [Java Wait for thread to finish](http://stackoverflow.com/questions/4691533/java-wait-for-thread-to-finish) – Matias Cicero Dec 16 '14 at 18:22
-
You may check if any of the 5 threads have finished, if not then sleep your main thread for a certain period of time. May be add a listener that would notify your main thread to wake up and spawn a new thread. – Syed Mauze Rehan Dec 16 '14 at 18:25
-
Well, I dont rly want to use join because I dont want to keep track of all threads alive. And yes, the main thread has to do this, so cant rly use a listener either. – Joseph Müller Dec 16 '14 at 18:26
-
1see in the list of answers in the link given by @MatiCicero .. CountDownLatch latch = new CountDownLatch(3); ... latch.await(); // Wait for countdown – LeTex Dec 16 '14 at 18:27
-
Then the only alternative I can think of is to poll and check if a thread is alive or not. – Sotirios Delimanolis Dec 16 '14 at 18:28
-
Or checkout this one: http://stackoverflow.com/questions/1323408/get-a-list-of-all-threads-currently-running-in-java – LeTex Dec 16 '14 at 18:30
-
Is it possible that what you actually want is a [thread pool of fixed size](http://docs.oracle.com/javase/7/docs/api/java/util/concurrent/ThreadPoolExecutor.html) 5? – 5gon12eder Dec 16 '14 at 18:31
1 Answers
1
Consider using thread pool. Anyway, the code below is doing what you are asking for.
import java.util.concurrent.atomic.AtomicInteger;
public class Main {
public static void main(String[] args) throws InterruptedException {
final AtomicInteger atomicInteger = new AtomicInteger(0);
for (;;) {
while (atomicInteger.get() < 5) {
atomicInteger.getAndIncrement();
Thread t = new Thread() {
public void run() {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
atomicInteger.getAndDecrement();
};
};
t.start();
}
Thread.sleep(100);
}
}
}
-
After all I just used a thread pool. But yeah, that would answer my question. – Joseph Müller Dec 17 '14 at 17:39