一战坤、Join解釋
Java對(duì)Thread的Join方法解釋:等待當(dāng)前線程終止。
public final void join() throws [InterruptedException]
Waits for this thread to die.
二抬旺、Demo
案例是一個(gè)計(jì)算兩個(gè)線程執(zhí)行完畢后的時(shí)間統(tǒng)計(jì)问芬。那么我們?cè)鯓哟_定兩個(gè)線程是否已經(jīng)執(zhí)行完畢呢?
可以通過線程Thread的Join方法來(lái)確定當(dāng)前的線程是否已經(jīng)執(zhí)行完畢类垫。
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是怎樣確定線程是否已經(jīng)完成
1.我們查看下Join方法的源碼是調(diào)用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;
}
}
}
從源碼發(fā)現(xiàn),Join方法是由主線程進(jìn)行調(diào)用的悉患,先檢測(cè)當(dāng)前子線程對(duì)象是否還在活動(dòng)狀態(tài)残家,如果是活動(dòng)狀態(tài),那么就調(diào)用子線程的wait方法售躁,使主線程進(jìn)入了等待的狀態(tài)坞淮,待子線程喚醒主線程,主線程在繼續(xù)執(zhí)行陪捷。
四回窘、執(zhí)行過程
捕獲.PNG