栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > Java面试题

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

Java面试题 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

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

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

代码如下
public class Test {


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方法

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/264327.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号