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

jia*_*afu 6 java multithreading join notify

thread.join()会叫thread.wait(),但谁和通知时(或者使用thread.notify()notifyAll())的thread.wait()

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

DaS*_*Stc 9

至于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;
}
Run Code Online (Sandbox Code Playgroud)

当在java中启动线程时,线程将是JavaThread的instanceof。

/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();
}
Run Code Online (Sandbox Code Playgroud)

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


Gra*_*ray 7

编辑:

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

while (isAlive()) {
    wait(0);
}
Run Code Online (Sandbox Code Playgroud)

notify()这个由处理Thread子系统.当run()方法结束时,notify()被称为上Thread对象.我不确定是否notify()可以看到实际调用的代码- 它似乎是在本机代码中完成的.


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

例如,以下代码将执行正常,并且join()调用将返回正常,没有任何wait()notify()调用.

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

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