Thread类join方法原理浅析

本文探讨了Java中Thread类的join方法,该方法用于在一个线程等待另一个线程完成执行。介绍了无限等待和有限等待两种重载形式,并通过代码示例展示了其使用方式。深入分析了join方法的源码,指出其基于wait方法实现,锁对象为调用线程本身,而线程的唤醒是由JVM在目标线程执行完毕时自动进行的。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

很多时候,一个线程的输入可能非常依赖于另外一个或者多个线程的输出,此时,这个线程就需要等待依赖的线程执行完毕,才能继续执行。Thread类提供了join方法来实现这个功能。Thread类对join方法提供了几种不同的重载版本,我们重点关心以下两种:

public final void join() throws InterruptedException
public final synchronized void join(long millis)
    throws InterruptedException

方法一表示无限等待,直到目标线程执行结束或者当前线程被中断(调用interrupt()方法);方法二表示有限时长的等待要么目标线程执行结束唤醒当前线程,要么等待时间截至或者被中断。

join方法的使用:假如线程一需要等待线程二执行结束,那么就在线程一中调用线程二的join()方法,如下代码所示:
代码1

public class JoinTest {
    public static void main(String[] args) throws InterruptedException{
        MyThread thread = new MyThread();
        thread.start();
        thread.join();
        System.out.println(thread.num);
    }

    private static class MyThread extends Thread{
        public int num = 0;
        @Override
        public void run() {
            for (int i = 0; i < 100000; i++) {
                num++;
            }
        }
    }
}

如我们所料,代码结果为100000。接下来深入到join方法源代码让我们它的具体实现原理是什么
代码2

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方法实现的。既然是wait方法那么必然有synchronized了,获取的是那个对象的监视器呢?我们可以看到这是一个synchronized修饰的成员方法,锁对象即为this,也就是代码1中的thread对象。那么锁的是哪一个线程呢,在哪个线程中调用的这个方法锁的就是谁了,显然就是主线程了!

问题还没有结束,我们调用的是join()方法,不带超时时间的。可以看到,millis=0时调用的是wait(0)方法即永久等待,是不会自己醒来的。那么当目标线程执行结束是谁将它唤醒的呢???事实上这个问题光看Java代码是找不答案的,线程的唤醒由jvm实现。注:wait(0)和join(0)的参数0不是代表不等待,而是永久等待。

// 位于/hotspot/src/share/vm/runtime/thread.cpp中
void JavaThread::exit(bool destroy_vm, ExitType exit_type) {
    // ...

    // Notify waiters on thread object. This has to be done after exit() is called
    // on the thread (if the thread is the last thread in a daemon ThreadGroup the
    // group should have the destroyed bit set before waiters are notified).
    // 有一个贼不起眼的一行代码,就是这行
    ensure_join(this);

    // ...
}


static void ensure_join(JavaThread* thread) {
    // We do not need to grap the Threads_lock, since we are operating on ourself.
    Handle threadObj(thread, thread->threadObj());
    assert(threadObj.not_null(), "java thread object must exist");
    ObjectLocker lock(threadObj, thread);
    // Ignore pending exception (ThreadDeath), since we are exiting anyway
    thread->clear_pending_exception();
    // Thread is exiting. So set thread_status field in  java.lang.Thread class to TERMINATED.
    java_lang_Thread::set_thread_status(threadObj(), java_lang_Thread::TERMINATED);
    // Clear the native thread instance - this makes isAlive return false and allows the join()
    // to complete once we've done the notify_all below
    java_lang_Thread::set_thread(threadObj(), NULL);

    // 重点看这句。
    lock.notify_all(thread);

    // Ignore pending exception (ThreadDeath), since we are exiting anyway
    thread->clear_pending_exception();
}

当线程thread执行完毕的时候,jvm会自动唤醒阻塞在thread对象上的线程,在我们的例子中也就是主线程。至此,thread线程对象被notifyall了,那么主线程也就能继续跑下去了。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值