gpt4 book ai didi

java - 当调用 thread.join() 时,谁以及何时通知 thread.wait()?

转载 作者:塔克拉玛干 更新时间:2023-11-03 04:56:32 24 4
gpt4 key购买 nike

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

我们知道thread join会等待线程完成,但是谁调用notify呢?

最佳答案

关于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中启动线程时,线程将是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();
}

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

关于java - 当调用 thread.join() 时,谁以及何时通知 thread.wait()?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9866193/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com