看了一下Thread的源码,join()是通过wait()实现的,看起来是this.wait(),可为什么是调用的线程停下来等待了呢,
首先tb.join() 是一个synchronized方法, 里面调用了wait(),这个过程的目的是让持有这个同步锁的线程进入等待,那么谁持有了这个同步锁呢?答案是主线程,因为主线程调用了tb.join()方法,相当于在tb.join()代码这块写了一个同步代码块,谁去执行了这段代码呢,是主线程,所以主线程被wait()了,如果tb.join()里面的代码,被写在了tb.run()方法里面,那么tb线程就会被wait()。就是这样子了,要看是谁执行了它,谁持有了它的锁wait()方法只会让持有锁的线程进入等待,而tb.start()并没有持有锁,所以并不会出现等待的状态。
所以说wait()实际上是让调用了此方法的线程进入等待队列,和调用哪个对象的wait()方法无关,考虑到wait()方法是Object类的,并且join()是通过wait()实现的,那么不要被Thread对象迷惑了,不是让被调用了join()的线程对象等待,而是让调用了join()的线程进入等待队列,即
b线程执行了a.join(),进入等待队列的是b而不是a。
并且在线程退出时有如下调用
// 位于/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);
// 同志们看到了没,别的不用看,就看这一句
// thread就是当前线程,是啥?就是刚才例子中说的threadA线程啊。
lock.notify_all(thread);
// Ignore pending exception (ThreadDeath), since we are exiting anyway
thread->clear_pending_exception();
}
确保了线程退出时会唤醒join()所阻塞的线程。
参考:
https://blog.csdn.net/u010983881/article/details/80257703
https://www.zhihu.com/question/44621343