ExecutorService exec = Executors.newCachedThreadPool();
for(int i = 0; i < 10; i++)
{
exec.execute(new Entrance(i));//obviously Entrance is another class which implements Runnable
}
TimeUnit.SECONDS.sleep(3); // this sleep code is very elegant!
exec.shutdown();
if(!exec.awaitTermination(250, TimeUnit.MILLISECONDS))
{
print("Some tasks were not terminated");
}
Some points to explain:
1)ExecutorService.awaitTermination() waits for each task to complete, and if they all complete before the timeout value, it returns true, otherwise it returns false to indicate that not all tasks have completed.