Create a list and wait for it.
List<Thread> threads = new ArrayList<Thread>(); for(int i=0;i<n;i++){ Thread t=new Thread(); t.start(); threads.add(t); } for(Thread t: threads) t.join();
However, using an ExecutorService might be a more elegant way to handle a thread pool.
ExecutorService es = Executors.newCachedThreadPool(); for(int i=0;i<n;i++) es.submit(new Task(n)); es.shutdown(); es.awaitTermination(timeout, TimeUnit.SECONDS);
Peter Lawrey
source share