join() 的作用:讓“主線程”等待“子線程”結(jié)束之后才能繼續(xù)運行叁鉴。
join()源碼示例:
public final void join() throws InterruptedException {
join(0);
}
public final synchronized void join(long millis)
throws InterruptedException {
long base = System.currentTimeMillis();
long now = 0;
if (millis < 0) {
throw new IllegalArgumentException("timeout value is negative");
}
if (millis == 0) {
while (isAlive()) {
wait(0);
}
} else {
while (isAlive()) {
long delay = millis - now;
if (delay <= 0) {
break;
}
wait(delay);
now = System.currentTimeMillis() - base;
}
}
}
源碼分析:
(01) 當millis==0時瞒大,會進入while(isAlive())循環(huán);即只要子線程是活的犬庇,主線程就不停的等待喳篇。
(02) isAlive()應該是判斷“子線程s”是不是Alive狀態(tài)敌买,而wait(0)的作用是讓“當前線程”等待藤乙,而這里的“當前線程”是指當前在CPU上運行的線程猜揪。所以,雖然是調(diào)用子線程的wait()方法坛梁,但是它是通過“主線程”去調(diào)用的而姐;所以,休眠的是主線程划咐,而不是“子線程”拴念!
示例:
public class JoinTest {
static class ThreadD extends Thread{
public ThreadD(String name){
super(name);
}
public void run(){
System.out.printf("%s start\n", this.getName());
//延時操作
for(int i=0; i<100000; i++)
;
System.out.printf("%s finish\n", this.getName());
}
}
public static void main(String[] args) {
try{
ThreadD t1 = new ThreadD("t1");
t1.start();
t1.join();
System.out.printf("%s finish\n", Thread.currentThread().getName());
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
運行結(jié)果:
t1 start
t1 finish
main finish