在A线程中调用了B线程的join()方法时,表示只有当B线程执行完毕时,A线程才能继续执行。
public class ThreadJoin {
public static void main(String[] args) {
Thread t1 = new Thread(()->{
IntStream.range(1,1000).forEach(i-> System.out.println(Thread.currentThread().getName()));
});
Thread t2 = new Thread(()->{
IntStream.range(1,1000).forEach(i-> System.out.println(Thread.currentThread().getName()));
});
t1.start();
t2.start();
try {
t1.join();
t2.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
Optional.of("All of task finish done").ifPresent(System.out::println);
IntStream.range(1,1000).forEach(i-> System.out.println(Thread.currentThread().getName()));
}
}
总结:
main线程会等到t1和t2线程执行完毕之后,才进行打印
public class ThreadJoin2 {
public static void main(String[] args) {
long startTime = System.currentTimeMillis();
Thread m1 = new Thread(new CaptureRunnable("m1", 10000L));
Thread m2 = new Thread(new CaptureRunnable("m2", 30000L));
Thread m3 = new Thread(new CaptureRunnable("m3", 15000L));
m1.start();
m2.start();
m3.start();
try {
m1.join();
m2.join();
m3.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
long endTime = System.currentTimeMillis();
System.out.println("save data start time is="+startTime+",endtime is="+endTime);
}
}
class CaptureRunnable implements Runnable{
private String machineName;
private long spendTime;
public CaptureRunnable(String machineName, long spendTime) {
this.machineName = machineName;
this.spendTime = spendTime;
}
@Override
public void run() {
try {
Thread.sleep(spendTime);
System.out.println(machineName+" completed data capture and successful spend time is" + spendTime);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
public String getResult(){
return machineName+ " finish";
}
}
总结:三个线程同时对三台机器进行数据采集,通过join方式,让这三个线程交替运行,最后mian线程记录最后一台机器采集数据完成的时间