一、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方法,使主线程进入了等待的状态,待子线程唤醒主线程,主线程在继续执行。