一、Join解釋
Java對Thread的Join方法解釋:等待當前線程終止。
public final void join() throws [InterruptedException]
Waits for this thread to die.
二、Demo
案例是一個計算兩個線程執行完畢后的時間統計。那么我們怎樣確定兩個線程是否已經執行完畢呢?
可以通過線程Thread的Join方法來確定當前的線程是否已經執行完畢。
final long objSize = 100;
private final static LinkedBlockingDeque<CompareDemoObj> queue = new LinkedBlockingDeque<>();
public void Join() throws InterruptedException{
Thread product = new Thread(new Runnable() {
@Override
public void run() {
for (int i = 0; i < objSize; i++) {
try {
queue.add( new CompareDemoObj());
} catch (Exception e) {
e.printStackTrace();
}
}
}
}) ;
Thread consumer = new Thread(new Runnable() {
@Override
public void run() {
if(queue.size()>0){
queue.remove();
}
}
});
long timeStart = System.currentTimeMillis();
product.start();
consumer.start();
product.join();
consumer.join();
long timeEnd = System.currentTimeMillis();
System.out.println((timeEnd - timeStart));
}
三、Join是怎樣確定線程是否已經完成
1.我們查看下Join方法的源碼是調用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;
}
}
}
從源碼發現,Join方法是由主線程進行調用的,先檢測當前子線程對象是否還在活動狀態,如果是活動狀態,那么就調用子線程的wait方法,使主線程進入了等待的狀態,待子線程喚醒主線程,主線程在繼續執行。
四、執行過程
捕獲.PNG