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

时间:2012-03-26 03:14:54

标签: java multithreading join notify

thread.join()会致电thread.wait(),但是thread.notify()通知notifyAll()thread.wait()的人和何时?

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

2 个答案:

答案 0 :(得分:7)

修改

哦,你在讨论Thread对象本身。在join()内,我们看到wait()。类似的东西:

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

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();

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

答案 1 :(得分:4)

对于linux的jdk7,你可以从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)会通知等待线程完成的所有线程。