线程加入

join()方法,等待其他线程终止。在当前线程(主线程)中调用另一个线程(子线程)的join()方法,则当前线程转入阻塞状态,直到另一个线程运行结束,当前线程再由阻塞转为就绪状态。

也就是主线程中,子线程调用了join()方法后面的代码,只有等到子线程结束了才能执行。

在很多情况下,主线程生成并起动了子线程,如果子线程里要进行大量的耗时的运算,主线程往往将于子线程之前结束。

如下例子:

 class JoinRunnable implements Runnable {
@Override
public void run() {
System.out.println("Child thread start.");
try {
for (int i = 1; i <= 5; i++) {
System.out.println("Child thread runing [" + i + "].");
Thread.sleep((int) (Math.random() * 100));
}
} catch (InterruptedException e) {
System.out.println("Child thread interrupted.");
}
System.out.println("Child thread end.");
}
} public class JoinDemo {
// main是主线程
public static void main(String args[]) {
System.out.println("Main thread start.");
new Thread(new JoinRunnable()).start();
System.out.println("Main thread end.");
}
}

执行结果:

Main thread start.
Main thread end.
Child thread start.
Child thread runing [1].
Child thread runing [2].
Child thread runing [3].
Child thread runing [4].
Child thread runing [5].
Child thread end.

如果主线程需要等待子线程执行完成之后再结束,这个时候就要用到join()方法了。

如下例子:

 class JoinRunnable implements Runnable {
@Override
public void run() {
System.out.println("Child thread start.");
try {
for (int i = 1; i <= 5; i++) {
System.out.println("Child thread runing [" + i + "].");
Thread.sleep((int) (Math.random() * 100));
}
} catch (InterruptedException e) {
System.out.println("Child thread interrupted.");
}
System.out.println("Child thread end.");
}
} public class JoinDemo {
// main是主线程
public static void main(String args[]) {
System.out.println("Main thread start.");
Thread t = new Thread(new JoinRunnable());
t.start();
try {
t.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("Main thread end.");
}
}

执行结果:

Main thread start.
Child thread start.
Child thread runing [1].
Child thread runing [2].
Child thread runing [3].
Child thread runing [4].
Child thread runing [5].
Child thread end.
Main thread end.

最新文章

  1. Socket开发框架之数据传输协议
  2. .NET软件开发与常用工具清单(转)
  3. static_cast、dynamic_cast、reinterpret_cast、const_cast以及C强制类型转换的区别
  4. linux C学习笔记05--信号量与共享内存(进程同步)
  5. JavaScript及C# URI编码详解
  6. What are the main disadvantages of Java Server Faces 2.0?
  7. LightOJ 1370 - Bi-shoe and Phi-shoe (欧拉函数思想)
  8. boost::xml——基本操作以及中文乱码解决方案
  9. MyEclipse常用设置笔记
  10. HW2.22
  11. C++ TinyXml操作(含源码下载)
  12. Python的if判断与while循环
  13. 初学c语言
  14. 常用硬件设备GUID
  15. C++ size_t 和size_type的区别
  16. 设计模式之创建类模式PK
  17. Flask路由&amp;视图
  18. 用XMLHttpRequest制作一个简易ajax
  19. SpringCloud-day02-服务消费者项目建立
  20. js基础-运算符

热门文章

  1. Sereja and Brackets CodeForces - 380C (树状数组+离线)
  2. python学习笔记(三)条件判断和循环
  3. 浅入深出Vue:文章列表
  4. 【vs2015发布程序】
  5. ant-design-vue 修改组件样式
  6. Mockito 2 关于打标(stubbing)
  7. 『HGOI 20190917』Cruise 题解 (计算几何+DP)
  8. Android NDK加载SD卡中的so
  9. [CSP-S模拟测试]:Weed(线段树)
  10. win7安装ElasticSearch集群