一、概述
- join的作用,让父线程等待子线程结束之后才能继续运行 ,join的兄弟线程依然是并行执行。
- 案列:健康信息检查:已收集3台集服务器信息,并记录第一台开始收集时间和最后一台结束收集时间。
二、代码
1、不使用join
package com.cfl.thread;
import sun.util.logging.resources.logging;
/**
* Join 让父线程等待子线程结束之后才能继续运行
* 健康信息检查:已收集5台集服务器信息,并记录第一台开始收集时间和最后一台结束收集时间
* @author chenfenli
*
*/
public class Thread5 {
public static void main(String[] args) throws Exception {
long startTime = System.currentTimeMillis();
Thread thread1 = new Thread(new HealthCollect("M1", 10000L));
Thread thread2 = new Thread(new HealthCollect("M2", 2000L));
Thread thread3 = new Thread(new HealthCollect("M3", 3000L));
thread1.start();
thread2.start();
thread3.start();
// thread1.join();
// thread1.join();
// thread1.join();
long endTime = System.currentTimeMillis();
System.out.println(endTime-startTime);
System.out.println(Thread.currentThread().getName());
}
public static class HealthCollect implements Runnable{
// 模拟计算机名称
private String machineName;
// 模拟收集时间
private long spendTime;
private HealthCollect(String machineName, long spendTime) {
this.machineName = machineName;
this.spendTime = spendTime;
}
public void run() {
try {
Thread.sleep(spendTime);
System.out.println(machineName + " successfully");
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
startTime: 1562513784764 endTime: 1562513784768 时间差: 4
main
M2 successfully
M3 successfully
M1 successfully
- 可以看到M1、M2、M3还没执行完成,main方法就执行完了,计算时间也不对,无法完成案列需求。
2、打开注释,使用join
thread1.join();
thread1.join();
thread1.join();
M2 successfully
M3 successfully
M1 successfully
startTime: 1562513984607 endTime: 1562513994611 时间差: 10004
main
- 可以看到只有当M1、M2、M3都执行完成之后,main方法才执行完成,并且正确的记录了开始时间和结束时间。join的兄弟线程依然是并行执行。