join加入

public class JoinDemo {
public volatile static int i = 0;
public static class AddThread extends Thread{
@Override
public void run() {
for (i=0;i<10000000;i++);
}
}
public static void main(String[] args) throws InterruptedException{
AddThread addThread = new AddThread();
addThread.start();
addThread.join();
System.out.println(i);
}
}
public class JoinDemo {
public static void main(String[] args) throws InterruptedException{
Thread threadA = new Thread(new Runnable() {
@Override
public void run() {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("child threadA over");
}
});
Thread threadB = new Thread(new Runnable() {
@Override
public void run() {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("child threadB over");
}
});
threadA.start();
threadB.start();
System.out.println("wait all thread over");
//等待子线程执行完毕
threadA.join();//主线程调用threadA的join()方法后被阻塞,等待threadA执行完毕
threadB.join();
System.out.println("all thread over");
//wait all thread over
//child threadA over
//child threadB over
//all thread over Thread threadOne = new Thread(new Runnable() {
@Override
public void run() {
System.out.println("threadOne begin run");
while (true){} //死循环
}
});
//获取主线程
final Thread mainThread = Thread.currentThread();
Thread threadTwo = new Thread(new Runnable() {
@Override
public void run() {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
//中断主线程
mainThread.interrupt();
System.out.println("threadTwo begin run");
}
});
threadOne.start();
threadTwo.start();
threadOne.join();
//threadOne begin run
//threadTwo begin run
//Exception in thread "main" java.lang.InterruptedException //在 threadOne 线程里面执行死循环,主线程调用 threadOne 的 join 方 法阻 塞 自己 等 待线程 threadOne 执行完毕,
// 待 threadTwo 休眠 ls 后会调用主线程的 interrupt() 方法设置主线程的中断标志,
// 从结果看在主线程中的 threadOne.join() 处会抛 出 InterruptedException 异常
}
}

最新文章

  1. javascript-组合模式
  2. C# String.Format格式说明
  3. Linux下添加硬盘,分区,格式化详解
  4. HD 1011 Starship Troopers(树上的背包)
  5. 转载css层级优先级。
  6. Java实现八皇后
  7. 关于git的文件内容冲突解决
  8. js split函数用法总结
  9. shell编程控制结构:expr、let、for、while、until、shift、if、case、break、continue、功能、select
  10. jQuery 1.10.2 and 2.0.3 Released
  11. 10- python 网络爬虫分析
  12. GO语言初探
  13. Python - 网络爬虫(Web Scraping)
  14. IIC双向电平转换电路设计
  15. 数据结构C语言版--单链表的基本功能实现
  16. 记录Linux中遇到的技巧
  17. 【python54--爬虫2】
  18. Thinkphp 3.1. 3 ueditor 1.4.3 添加水印
  19. 【Devops】【docker】【CI/CD】1.docker搭建Gitlab环境
  20. C#之使用AutoUpdater自动更新客户端

热门文章

  1. Hadoop搭建完全分布式
  2. Restful风格接口浅析
  3. Webpack 4 和单页应用入门
  4. springmvc把对象放到session中
  5. 【2019 Multi-University Training Contest 3】
  6. LUOGU P4088 [USACO18FEB]Slingshot(线段树)
  7. 使用lambda编写九九乘法表
  8. [bzoj3462]DZY Loves Math II (美妙数学+背包dp)
  9. 使用Microsoft.Practices.Unity 依赖注入
  10. 重写ArcGIS的TiledMapServiceLayer调用天地图瓦片