java实现子线程全部结束主线程继续执行

匿名网友 匿名网友 发布于: 2015-08-30 00:00:00
阅读 129 收藏 0 点赞 0 评论 0

在主线程中启动多个子线程 要让主线程等待所有子线程都结束才能继续执行

代码如下
public class Test {

/**
* @param args
*/
public static void main(String[] args) {
Test t = new Test();
mainThread mt = t.new mainThread();
mt.run();
}

class mainThread implements Runnable {

@Override
public void run() {
System.out.println(“main begin”);
childThread[] cts = new childThread[200];
for(int i = 0;i<200;i++){
childThread ct = new childThread();
ct.start();
cts = ct;
}

try {
for(int i = 0;i<200;i++){
cts.join();
}
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

System.out.println(“main end”);
}

}

class childThread extends Thread implements Runnable {

@Override
public void run() {
String str = “啊”;
for (int i = 0; i < 1000; i++) {
str += “!”;
}

System.out.println(“child thread end”);
}

}
}

输出结果

main begin
child thread end
child thread end
…200次
child thread end
main end

实际上就是用到了Thread类的join方法

评论列表
文章目录