文章目录
join方法的作用 用法
- join方法的作用 用法
- join普通用法的demo
作用: 因为新的线程加入了我们, 所以我们要等待他执行完再执行. (例如等待某些初始化的线程执行完毕, 再执行. )
用法: main线程等待子线程执行完毕. (注意是main线程等待子线程)
join普通用法的demo如下的代码, 子线程使用了join. 因此main线程会进行等待子线程执行完毕, 才会打印出"所有子线程执行完毕"
package com.thread.threadobjectclasscommonmethods;
/**
* 类名称:Join
* 类描述: 演示join,注意语句输出顺序,会变化。
*
* @author: https://javaweixin6.blog.csdn.net/
* 创建时间:2020/8/30 13:27
* Version 1.0
*/
public class Join {
public static void main(String[] args) throws InterruptedException {
Thread thread1 = new Thread(new Runnable() {
@Override
public void run() {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName() + "执行完毕");
}
},"thread1");
Thread thread2 = new Thread(new Runnable() {
@Override
public void run() {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName() + "执行完毕");
}
},"thread2");
thread1.start();
thread2.start();
System.out.println("开始等待子线程运行完毕");
thread1.join();
thread2.join();
System.out.println("所有子线程执行完毕");
}
}
程序运行的结果如下 如果把join线程去掉, 那么就会出现如下的线程, main线程并没有等待子线程, 直接打印出了
"所有子线程执行完毕"