谁和什么时候调用thread.join()时通知thread.wait()?

thread.join()将调用thread.wait() ,但是谁和何时通知(使用thread.notify()notifyAll()thread.wait()

我们知道,线程连接将等待线程完成,但是谁调用了通知呢?

编辑:

哦,你在谈论Thread对象本身。 在join()里面我们看到了wait() 。 就像是:

 while (isAlive()) { wait(0); } 

对此的notify()Thread子系统处理。 当run()方法完成时,在Thread对象上调用notify() 。 我不确定是否可以看到实际调用notify()的代码 – 它似乎是在本机代码中完成的。


没有用户代码需要在该Thread对象上调用notify() 。 Java Thread代码在内部处理这个问题。 线程完成后,将返回join()调用。

例如,以下代码将执行正常,并且join()调用将返回正常,而不进行任何wait()notify()调用。

 Thread thread = new Thread(new Runnable() { public void run() { // no-op, just return immediately } }); thread.start(); thread.join(); 

重要的是要注意,这种行为可能不应该依赖。 notify()调用是线程系统的内部调用。 如果您正在等待线程完成,则应使用join()

至于jdk7 for linux,你可以从openjdk的源代码中得到答案。

/jdk7/hotspot/src/os/linux/vm/os_linux.cpp

 int ret = pthread_create(&tid, &attr, (void* (*)(void*)) java_start, thread); static void *java_start(Thread *thread) { ... thread->run(); return 0; } 

当在java中启动线程时,该线程将是JavaThread的实例。

/jdk7/hotspot/src/share/vm/runtime/thread.cpp

 void JavaThread::run() { ... thread_main_inner(); } void JavaThread::thread_main_inner() { ... this->exit(false); delete this; } 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(); } 

所以lock.notify_all(thread)将通知等待线程完成的所有线程。