Thread.join方法
我們知道線程是搶占運(yùn)行時(shí)的,比如同時(shí)執(zhí)行兩個(gè)線程(也不能完全同時(shí),比如一個(gè)在前一行,一個(gè)在后一行),都執(zhí)行一個(gè)for循環(huán)迭代100次,打印當(dāng)前線程號(hào),你會(huì)發(fā)現(xiàn)每次執(zhí)行的結(jié)果都不一樣,兩個(gè)線程的線程號(hào)互相穿插著打印出來了,每次穿插的順序都不同。
Thread的join方法就可以把交替執(zhí)行的線程合并成順序執(zhí)行,比如在B中調(diào)用了A,A join進(jìn)來了,那么就要等待A執(zhí)行一段時(shí)間,才繼續(xù)執(zhí)行B。注意,調(diào)用join的必須是線程A,不能是線程B,因?yàn)锽跟自己是同一個(gè)線程嘛。。然后參數(shù)mills代表B等待A執(zhí)行的duration,如果設(shè)置成0,就直到A執(zhí)行完了才執(zhí)行B。
join的主要實(shí)現(xiàn)是通過lock.wait,當(dāng)B線程調(diào)用A的 join,B會(huì)拿到A的鎖。
wait方法是native方法了,wait跟sleep有點(diǎn)像,sleep阻塞當(dāng)前線程,不釋放鎖。wait釋放鎖。用notify喚醒。
/**
* Waits at most {@code millis} milliseconds for this thread to
* die. A timeout of {@code 0} means to wait forever.
* 在這個(gè)線程死之前,最多等待mills長度的時(shí)間
* This implementation uses a loop of {@code this.wait} calls
* conditioned on {@code this.isAlive}. As a thread terminates the
* {@code this.notifyAll} method is invoked. It is recommended that
* applications not use {@code wait}, {@code notify}, or
* {@code notifyAll} on {@code Thread} instances.
*/
public final void join(long millis) throws InterruptedException {
synchronized(lock) {
long base = System.currentTimeMillis();
long now = 0;
if (millis < 0) {
throw new IllegalArgumentException("timeout value is negative");
}
if (millis == 0) {
while (isAlive()) {
//一直等待的這個(gè)線程執(zhí)行完
lock.wait(0);
}
} else {
while (isAlive()) {
long delay = millis - now;
if (delay <= 0) {
break;
}
//等待delay時(shí)間
lock.wait(delay);
now = System.currentTimeMillis() - base;
}
}
}
}