Thread的join的作用
案例代码:
package com.concurrency;
/**
* join的作用: 等thread线程均执行完成,才处理main线程
*
*/
public class ThreadJoinDemo {
public static void main(String[] args) throws InterruptedException {
long startTimeStamp = System.currentTimeMillis();
Thread t1 = new Thread(new CaptureRunnable("M1", 1000L));
Thread t2 = new Thread(new CaptureRunnable("M2", 2000L));
Thread t3 = new Thread(new CaptureRunnable("M3", 1500L));
t1.start();
t2.start();
t3.start();
t1.join();
t2.join();
t3.join();
long endTimeStamp = System.currentTimeMillis();
System.out.printf("save data begin timestamp is:%s, end timestamp is:%s",startTimeStamp,endTimeStamp);
}
}
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");
} catch (InterruptedException e){
e.printStackTrace();
}
}
}
结果:
代码解读:
join加在t1,t2,t3 后,才能执行main线程