主线程 如果判断 N个子线程都执行完了?

需求:一个方法(主线程)开启了N个子线程,每个子线程去执行各自的任务,且执行的时间不一样,现在主线程需要将所有子线程执行完后的结果进行处理,并返回。

那如果判断所有的子线程都执行完了呢?
目前我的做法是:

            TestThread t2= new TestThread();
    TestThread t3= new TestThread();
    TestThread t1= new TestThread();
    System.out.println("start...");
    t1.start();
    t2.start();
    t3.start();
    try{
        t1.join();
        t2.join();
        t3.join();

                  //此处得到t1,t2,t3,的执行结果,
                  //返回处理后的最终结果。

    }catch(Exception e){

    }

    System.out.println("end!!!");

现在,我是不知道这样处理性能上好不好, 因为调用这个是很需要性能好, 希望时间上最短好越好,因为可能调用的比较频繁,调用者需要将结果返回页面的。 
 求大家给一个好的解决方法或是思路。
 谢谢!!!

如果不考虑线程的复用性,直接做个ThreadGroup就能很容易做个循环判断出来线程是否执行完了
ThreadPoolExecutor 主要是考虑线程的复用

使用 CountDownLatch

[code="java"]
class MyJob implements Runnable{
CountDownLatch cdl;
MyJob(CountDownLatch cdl){
this.cdl = cdl;
}
@Override
public void run() {
try{
//do your job
}finally{
cdl.countDown();
}
}
}
void doMuiltipleJobs(){
int N=3;
CountDownLatch cdl = new CountDownLatch(N);
Thread t1 = new Thread(new MyJob(cdl));
Thread t2 = new Thread(new MyJob(cdl));
Thread t3 = new Thread(new MyJob(cdl));
t1.start();
t2.start();
t3.start();
try {
cdl.await();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
[/code]

如果上述MyJob是很频繁执行的,为了提高性能,你可以它们放到线程池里执行。

:D

ExecutorCompletionService

CountDownLatch CountDownLatch

方案1:线程组,不过不怎么推荐,Thinking in Java里面也只是一句话带过的。
方案2:Java的CyclicBarrier类,这个类就是专门解决你这个问题的。
具体用法:google。