采用CountDownLatch类来实现
主线程
package test;
import java.util.concurrent.CountDownLatch;
public class Main {
/**
*
* @author Administrator/2012-3-1/上午09:36:55
*/
public static void main(String[] args) {
int threadNum = 10;
CountDownLatch threadSignal = new CountDownLatch(threadNum);// 初始化countDown
for (int i = 0; i < threadNum; i++) {// 开threadNum个线程
Thread t = new ImportThread(i,threadSignal);
t.start();
}
try {
threadSignal.await();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}// 等待所有子线程执行完
System.out.println(Thread.currentThread().getName() + "结束.");// 打印结束标记
}
}
子线程:
package test;
import java.util.concurrent.CountDownLatch;
public class ImportThread extends Thread {
private CountDownLatch threadsSignal;
private int index;
public ImportThread(int index,CountDownLatch threadsSignal) {
this.threadsSignal = threadsSignal;
this.index=index;
}
@Override
public void run() {
System.out.println(Thread.currentThread().getName() + "开始...");
// Do somethings
System.out.println(Thread.currentThread().getName()+"do execute ...");
threadsSignal.countDown();// 线程结束时计数器减1
System.out.println(Thread.currentThread().getName() + "结束. 还有" + threadsSignal.getCount() + " 个线程");
}
}