1、jion
1、概念
当前线程,等待其调用join()方法的线程结束后继续执行。
/**
* @ClassName ThreadJoin
* @Description join demo
* @Author WL
* @Date 2020/8/23 22:39
*/
public class ThreadJoin {
public static void main(String[] args) throws InterruptedException {
Thread t1 = new Thread(() -> {
IntStream.range(1, 1000).forEach(i -> System.out.println(Thread.currentThread().getName() + "--->"+i));
});
t1.start();
t1.join();
IntStream.range(1, 1000).forEach(i -> System.out.println(Thread.currentThread().getName() + "--->"+i));
}
}
可以设置等待时间
/**
* @ClassName ThreadJoin
* @Description join demo
* @Author WL
* @Date 2020/8/23 22:39
*/
public class ThreadJoin {
public static void main(String[] args) throws InterruptedException {
Thread t1 = new Thread(() -> {
IntStream.range(1, 1000).forEach(i -> System.out.println(Thread.currentThread().getName() + "--->"+i));
});
t1.start();
t1.join();
IntStream.range(1, 1000).forEach(i -> System.out.println(Thread.currentThread().getName() + "--->"+i));
}
}
2、业务场景
对多台设备进行数据采集,每个线程采集一台设备的数据,数据量不同,花费时间也是不同的,但是存入数据时要求结束时间是一致的。
public class ThreadJoin3 {
public static void main(String[] args) throws InterruptedException {
//开始采集时间
long startTime=System.currentTimeMillis();
Thread t1 = new Thread(new CaptureRunnable("M1", 5_000L));
Thread t2 = new Thread(new CaptureRunnable("M2", 10_000L));
Thread t3 = new Thread(new CaptureRunnable("M3", 20_000L));
t1.start();
t2.start();
t3.start();
t1.join();
t2.join();
t3.join();
long endTime=System.currentTimeMillis();
System.out.println("所有机器数据采集结束,开始时间:"+startTime+"结束时间:"+endTime);
}
}
//执行数据采集任务
class CaptureRunnable implements Runnable {
private String machineName;
private Long costTime;
public CaptureRunnable(String machineName, Long costTime) {
this.machineName = machineName;
this.costTime = costTime;
}
@Override
public void run() {
System.out.println(machineName + "数据采集开始执行");
try {
Thread.sleep(costTime);
System.out.println(machineName + "数据采集结束,花费时间:" + costTime);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}