转载自:http://blog.csdn.net/jeffhtlee/article/details/12751825
- Java的线程是如何创建的,是直接调用OS的API,还是有自己的“抽象线程”?
先看java.lang.Thread.java中的start()方法:
- public synchronized void start()
- {
- ...
- start0();
- ...
- }
- private native void start0();
解压后找到jdk\src\share\native\java\lang\Thread.c并查看,方法start0()映射到了JVM_StartThread这个方法中:
- static JNINativeMethod methods[] =
- {
- {"start0", "()V", (void *)&JVM_StartThread},
- ..
- }
在hotspot\src\share\vm\prims\jvm.cpp查看JVM_StartThread的实现:
- JVM_ENTRY(void, JVM_StartThread(JNIEnv* env, jobject jthread))
- JavaThread *native_thread = NULL;
- ...
- native_thread = new JavaThread(&thread_entry, sz);
- ...
- Thread::start(native_thread);
- JVM_END
在hotspot\src\share\vm\runtime\thread.cpp中查看JavaThread的实现:
- JavaThread::JavaThread(ThreadFunction entry_point, size_t stack_sz) : ...
- {
- ...
- os::create_thread(this, thr_type, stack_sz);
- }
- void Thread::start(Thread* thread)
- {
- ...
- os::start_thread(thread);
- }
在hotspot\src\os目录下可以看到windows, linux, solaris和posix的实现,先检查linux\vm\os_linux.cpp
- bool os::create_thread(Thread* thread, ThreadType thr_type, size_t stack_size)
- {
- ...
- int ret = pthread_create(&tid, &attr, (void* (*)(void*)) java_start, thread);
- ...
- }
所以问题也有答案了: 通过调用平台的API创建一个线程!