Join:等待该线程执行完再继续(Waits for this thread to die)
public class TestJoin {
public static void main(String[] args) {
CustomThread t1 = new CustomThread("t1");
CustomThread t2 = new CustomThread("t2");
CustomThread t3 = new CustomThread("t3");
t1.start();
try {
t1.join(); // main thread等待t1执行完在继续执行
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("go on....");
t2.start();
t3.start();
}
}
class CustomThread extends Thread {
public CustomThread(String name){
super(name);
}
public void run(){
for(int i=0;i < 5;i++){
try {
Thread.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName() + "执行:" + (i+1));
}
}
}
输出结果如下:
t1执行:1
t1执行:2
t1执行:3
t1执行:4
t1执行:5
go on....
t3执行:1
t2执行:1
t3执行:2
t2执行:2
t3执行:3
t2执行:3
t3执行:4
t2执行:4
t3执行:5
t2执行:5