本文分享自华为云社区《Thread.start() ,工作这么久,还不知道它是怎么让线程跑起来的!》,作者:小傅哥。
面试官:我考你个题,看看你进大厂的几率大不。嗯... Java 线程如何启动的?
谢飞机:如何启动的?start 启动的!
面试官:还有吗?
谢飞机:嗯…,没了!
面试官:嗯,可能会与不会这一个题并不会让你代码有多牛、有多好,但是你的技术栈深度和广度,决定你的编程职业生涯是否有一条康庄大道。还是要多努力!
new Thread(() -> {
// todo
}).start();
咳咳,Java 的线程创建和启动非常简单,但如果问一个线程是怎么启动起来的往往并不清楚,甚至不知道为什么启动时是调用start(),而不是调用run()方法呢?
那么,为了让大家有一个更直观的认知,我们先站在上帝视角。把这段 Java 的线程代码,到 JDK 方法使用,以及 JVM 的相应处理过程,展示给大家,以方便我们后续逐步分析。
以上,就是一个线程启动的整体过程分析,会涉及到如下知识点:
接下来,我们就开始逐步分析每一步源码的执行内容,从而了解线程启动过程。
如图 19-2 是线程的启动过程时序图,整体的链路较长,会涉及到 JVM 的操作。核心源码如下:
new Thread(() -> {
// todo
}).start();
// JDK 源码
public synchronized void start() {
if (threadStatus != 0)
throw new IllegalThreadStateException();
group.add(this);
boolean started = false;
try {
start0();
started = true;
} finally {
try {
if (!started) {
group.threadStartFailed(this);
}
} catch (Throwable ignore) {}
}
}
// 本地方法 start0
private native void start0();
// 注册本地方法
public class Thread implements Runnable {
/* Make sure registerNatives is the first thing <clinit> does. */
private static native void registerNatives();
static {
registerNatives();
}
// ...
}
registerNatives,本地方法定义在 Thread.c 中,以下是定义的核心源码:
static JNINativeMethod methods[] = {
{"start0", "()V", (void *)&JVM_StartThread},
{"stop0", "(" OBJ ")V", (void *)&JVM_StopThread},
{"isAlive", "()Z", (void *)&JVM_IsThreadAlive},
{"suspend0", "()V", (void *)&JVM_SuspendThread},
{"resume0", "()V", (void *)&JVM_ResumeThread},
{"setPriority0", "(I)V", (void *)&JVM_SetThreadPriority},
{"yield", "()V", (void *)&JVM_Yield},
{"sleep", "(J)V", (void *)&JVM_Sleep},
{"currentThread", "()" THD, (void *)&JVM_CurrentThread},
{"interrupt0", "()V", (void *)&JVM_Interrupt},
{"holdsLock", "(" OBJ ")Z", (void *)&JVM_HoldsLock},
{"getThreads", "()[" THD, (void *)&JVM_GetAllThreads},
{"dumpThreads", "([" THD ")[[" STE, (void *)&JVM_DumpThreads},
{"setNativeName", "(" STR ")V", (void *)&JVM_SetNativeThreadName},
};
JVM_ENTRY(void, JVM_StartThread(JNIEnv* env, jobject jthread))
JVMWrapper("JVM_StartThread");
JavaThread *native_thread = NULL;
// 创建线程
native_thread = new JavaThread(&thread_entry, sz);
// 启动线程
Thread::start(native_thread);
JVM_END
thread_entry,线程入口
static void thread_entry(JavaThread* thread, TRAPS) {
HandleMark hm(THREAD);
Handle obj(THREAD, thread->threadObj());
JavaValue result(T_VOID);
JavaCalls::call_virtual(&result,
obj,
KlassHandle(THREAD, SystemDictionary::Thread_klass()),
vmSymbols::run_method_name(),
vmSymbols::void_method_signature(),
THREAD);
}
重点,在创建线程引入这个线程入口的方法时,thread_entry 中包括了 Java 的回调函数 JavaCalls::call_virtual。这个回调函数会由 JVM 调用。
vmSymbols::run_method_name(),就是那个被回调的方法,源码如下:
#define VM_SYMBOLS_DO(template, do_alias)
template(run_method_name, "run")
native_thread = new JavaThread(&thread_entry, sz);
接下来,我们继续看 JavaThread 的源码执行内容。
JavaThread::JavaThread(ThreadFunction entry_point, size_t stack_sz) :
Thread()
#if INCLUDE_ALL_GCS
, _satb_mark_queue(&_satb_mark_queue_set),
_dirty_card_queue(&_dirty_card_queue_set)
#endif // INCLUDE_ALL_GCS
{
if (TraceThreadEvents) {
tty->print_cr("creating thread %p", this);
}
initialize();
_jni_attach_state = _not_attaching_via_jni;
set_entry_point(entry_point);
// Create the native thread itself.
// %note runtime_23
os::ThreadType thr_type = os::java_thread;
thr_type = entry_point == &compiler_thread_entry ? os::compiler_thread :os::java_thread;
os::create_thread(this, thr_type, stack_sz);
}
源码:
众所周知,JVM 是个啥!,所以它的 OS 服务实现,Liunx 还有 Windows 等,都会实现线程的创建逻辑。这有点像适配器模式
os_linux -> os::create_thread
bool os::create_thread(Thread* thread, ThreadType thr_type, size_t stack_size) {
assert(thread->osthread() == NULL, "caller responsible");
// Allocate the OSThread object
OSThread* osthread = new OSThread(NULL, NULL);
// Initial state is ALLOCATED but not INITIALIZED
osthread->set_state(ALLOCATED);
pthread_t tid;
int ret = pthread_create(&tid, &attr, (void* (*)(void*)) java_start, thread);
return true;
}
static void *java_start(Thread *thread) {
// 线程ID
int pid = os::current_process_id();
// 设置线程
ThreadLocalStorage::set_thread(thread);
// 设置线程状态:INITIALIZED 初始化完成
osthread->set_state(INITIALIZED);
// 唤醒所有线程
sync->notify_all();
// 循环,初始化状态,则一致等待 wait
while (osthread->get_state() == INITIALIZED) {
sync->wait(Mutex::_no_safepoint_check_flag);
}
// 等待唤醒后,执行 run 方法
thread->run();
return 0;
}
JVM_ENTRY(void, JVM_StartThread(JNIEnv* env, jobject jthread))
JVMWrapper("JVM_StartThread");
JavaThread *native_thread = NULL;
// 创建线程
native_thread = new JavaThread(&thread_entry, sz);
// 启动线程
Thread::start(native_thread);
JVM_END
void Thread::start(Thread* thread) {
trace("start", thread);
if (!DisableStartThread) {
if (thread->is_Java_thread()) {
java_lang_Thread::set_thread_status(((JavaThread*)thread)->threadObj(),
java_lang_Thread::RUNNABLE);
}
// 不同的 OS 会有不同的启动代码逻辑
os::start_thread(thread);
}
}
void os::start_thread(Thread* thread) {
// guard suspend/resume
MutexLockerEx ml(thread->SR_lock(), Mutex::_no_safepoint_check_flag);
OSThread* osthread = thread->osthread();
osthread->set_state(RUNNABLE);
pd_start_thread(thread);
}
void os::pd_start_thread(Thread* thread) {
OSThread * osthread = thread->osthread();
assert(osthread->get_state() != INITIALIZED, "just checking");
Monitor* sync_with_child = osthread->startThread_lock();
MutexLockerEx ml(sync_with_child, Mutex::_no_safepoint_check_flag);
sync_with_child->notify();
}
// The first routine called by a new Java thread
void JavaThread::run() {
// ... 初始化线程操作
thread_main_inner();
}
void JavaThread::thread_main_inner() {
if (!this->has_pending_exception() &&
!java_lang_Thread::is_stillborn(this->threadObj())) {
{
ResourceMark rm(this);
this->set_native_thread_name(this->get_thread_name());
}
HandleMark hm(this);
this->entry_point()(this, this);
}
DTRACE_THREAD_PROBE(stop, this);
this->exit(false);
delete this;
}
版权说明 : 本文为转载文章, 版权归原作者所有 版权申明
原文链接 : https://blog.csdn.net/devcloud/article/details/121650192
内容来源于网络,如有侵权,请联系作者删除!