who and when notify the thread.wait() when thread.join() is called?

前端 未结 2 1247
夕颜
夕颜 2020-12-03 02:31

thread.join() will call thread.wait(), but who and when notifies (either with thread.notify() or notifyAll()) the t

2条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-12-03 03:02

    As for jdk7 for linux, you can get the answer from the source code of 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;
    }
    

    and when start thread in java, the thread will be instanceof 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();
    }
    

    so lock.notify_all(thread) will notify all threads whose wait for the thread to finish.

提交回复
热议问题