如何确保退出所有子类线程?

时间:2013-12-12 20:41:45

标签: java multithreading runnable

有 -

for (int i = 0; i<10 ; i++) {
            Runnable r = new Runnable(){...}
            new Thread(r).start();
        } 
// I want to continue here only after all the subclass threads before exited . 
...

如何在for部分之后继续之前确保所有子类线程都已退出?

除了保留Runnable中的所有List<Runnable>并最终检查每个元素的isAlive()之外,是否存在任何解决方案?

2 个答案:

答案 0 :(得分:3)

  

在继续执行for section之后,如何确保所有子类线程都退出?

我会使用ExecutorService类。请参阅他们的Java tutorial。类似的东西:

// create a thread pool with 10 workers
ExecutorService threadPool = Executors.newFixedThreadPool(10);
// or you can create an open-ended thread pool
// ExecutorService threadPool = Executors.newCachedThreadPool();
for (int i = 0; i < 10; i++) {
   threadPool.submit(new Runnable(){...});
}
// once we have submitted all jobs to the thread pool, it should be shutdown
threadPool.shutdown();

然后你可以等待他们完成:

threadPool.awaitTermination(Long.MAX_VALUE, TimeUnit.MILLISECONDS);

如果您仍然想要自己创建线程,那么通常会将其保留在List中并在每个线程上调用join()

List<Thread> threadList = new ArrayList<Thread>();
for (int i = 0; i < 10; i++) {
   Thread thread = new Thread(new Runnable(){...});
   thread.start();
   threadList.add(thread);
}
// this waits for all of the threads to finish before continuing
for (Thread thread : threadList) {
   thread.join();
}

答案 1 :(得分:0)

看看CountDownLatch。当你想要等待N个线程完成某些事情时,这非常棒。