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