I've run into a problem which I hope you gurus can help with.
I'm designing a multi threaded Java application which I would like to limit the number of spawned threads to 5 at any one time. The main() program should paused and wait until a thread is available from the pool until resuming it's process.
At the moment here is what I have come up with BUT it seems that the way I am detecting the number of active threads is not very accurate.
Just wondering if there is another way to do this.
ExecutorService pool = Executors.newFixedThreadPool(5);
for(int i=0; i<10000; i++){
System.out.println("current number of threads: "+((ThreadPoolExecutor)pool).getActiveCount());
while(true){
if (((ThreadPoolExecutor)pool).getActiveCount() < 5)
break;
Thread.sleep(TimeUnit.SECONDS.toMillis(1));
System.out.println("waiting ..... "+((ThreadPoolExecutor)pool).getActiveCount());
}
Runnable sampleThread = new SampleThread(100);
pool.submit(sampleThread );
}
**************************************************
** Output:
**************************************************
current number of threads: 0
current number of threads: 1
current number of threads: 1
current number of threads: 1
current number of threads: 1
Is there an alternative way to achieve what i'm trying to do ? I did some research and nothing quite fits the bill.
Thanks in Advance, Edmond