线程类详解

java 线程的启动。

java 线程的启动是由内部的start0 这个native方法都是由 JVM 负责实现的

  • java.lang.Thread

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
     public synchronized void start() {
    /**
    * This method is not invoked for the main method thread or "system"
    * group threads created/set up by the VM. Any new functionality added
    * to this method in the future may have to also be added to the VM.
    *
    * A zero status value corresponds to state "NEW".
    */
    if (threadStatus != 0)
    throw new IllegalThreadStateException();

    /* Notify the group that this thread is about to be started
    * so that it can be added to the group's list of threads
    * and the group's unstarted count can be decremented. */
    group.add(this);

    boolean started = false;
    try {
    // 调用下面的 native 方法。
    start0();
    started = true;
    } finally {
    try {
    if (!started) {
    group.threadStartFailed(this);
    }
    } catch (Throwable ignore) {
    /* do nothing. If start0 threw a Throwable then
    it will be passed up the call stack */
    }
    }
    }
  • Thread.c

    Thread 类的 JNI 接口

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    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},
    {"countStackFrames", "()I", (void *)&JVM_CountStackFrames},
    {"interrupt0", "()V", (void *)&JVM_Interrupt},
    {"isInterrupted", "(Z)Z", (void *)&JVM_IsInterrupted},
    {"holdsLock", "(" OBJ ")Z", (void *)&JVM_HoldsLock},
    {"getThreads", "()[" THD, (void *)&JVM_GetAllThreads},
    {"dumpThreads", "([" THD ")[[" STE, (void *)&JVM_DumpThreads},
    {"setNativeName", "(" STR ")V", (void *)&JVM_SetNativeThreadName},
    };
  • jvm.cpp

    jvm.cpp

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    67
    68
    69
    70
    71
    72
    JVM_ENTRY(void, JVM_StartThread(JNIEnv* env, jobject jthread))
    JVMWrapper("JVM_StartThread");
    JavaThread *native_thread = NULL;

    // We cannot hold the Threads_lock when we throw an exception,
    // due to rank ordering issues. Example: we might need to grab the
    // Heap_lock while we construct the exception.
    bool throw_illegal_thread_state = false;

    // We must release the Threads_lock before we can post a jvmti event
    // in Thread::start.
    {
    // Ensure that the C++ Thread and OSThread structures aren't freed before
    // we operate.
    MutexLocker mu(Threads_lock);

    // Since JDK 5 the java.lang.Thread threadStatus is used to prevent
    // re-starting an already started thread, so we should usually find
    // that the JavaThread is null. However for a JNI attached thread
    // there is a small window between the Thread object being created
    // (with its JavaThread set) and the update to its threadStatus, so we
    // have to check for this
    if (java_lang_Thread::thread(JNIHandles::resolve_non_null(jthread)) != NULL) {
    throw_illegal_thread_state = true;
    } else {
    // We could also check the stillborn flag to see if this thread was already stopped, but
    // for historical reasons we let the thread detect that itself when it starts running

    jlong size =
    java_lang_Thread::stackSize(JNIHandles::resolve_non_null(jthread));
    // Allocate the C++ Thread structure and create the native thread. The
    // stack size retrieved from java is signed, but the constructor takes
    // size_t (an unsigned type), so avoid passing negative values which would
    // result in really large stacks.
    size_t sz = size > 0 ? (size_t) size : 0;
    // thread_entry 是一个获取线程入口点的函数(run)
    native_thread = new JavaThread(&thread_entry, sz);

    // At this point it may be possible that no osthread was created for the
    // JavaThread due to lack of memory. Check for this situation and throw
    // an exception if necessary. Eventually we may want to change this so
    // that we only grab the lock if the thread was created successfully -
    // then we can also do this check and throw the exception in the
    // JavaThread constructor.
    if (native_thread->osthread() != NULL) {
    // Note: the current thread is not being used within "prepare".
    native_thread->prepare(jthread);
    }
    }
    }

    if (throw_illegal_thread_state) {
    THROW(vmSymbols::java_lang_IllegalThreadStateException());
    }

    assert(native_thread != NULL, "Starting null thread?");

    if (native_thread->osthread() == NULL) {
    // No one should hold a reference to the 'native_thread'.
    delete native_thread;
    if (JvmtiExport::should_post_resource_exhausted()) {
    JvmtiExport::post_resource_exhausted(
    JVMTI_RESOURCE_EXHAUSTED_OOM_ERROR | JVMTI_RESOURCE_EXHAUSTED_THREADS,
    "unable to create new native thread");
    }
    THROW_MSG(vmSymbols::java_lang_OutOfMemoryError(),
    "unable to create new native thread");
    }

    Thread::start(native_thread);

    JVM_END
1
2
3
4
5
6
7
8
9
10
11
12
13
static void thread_entry(JavaThread* thread, TRAPS) {
HandleMark hm(THREAD);
Handle obj(THREAD, thread->threadObj());
JavaValue result(T_VOID);

// 这个调用应该就是 调用 Thread.run 方法。
JavaCalls::call_virtual(&result,
obj,
KlassHandle(THREAD, SystemDictionary::Thread_klass()),
vmSymbols::run_method_name(),
vmSymbols::void_method_signature(),
THREAD);
}
vmSymbols::run_method_name() 在其中 jdk7u-hotspot/src/share/vm/classfile/vmSymbols.hpp 文件中,其中就是 "run" 代表 java Thread 类中的 run 方法。 这份c++代码中使用到两个 c++ 类, JavaThread 和 Thread。
  • JavaThread

    JavaThread 这个文件中定义的类有:

    // Class hierarchy
    // - Thread
    //   - NamedThread
    //     - VMThread
    //     - ConcurrentGCThread
    //     - WorkerThread
    //       - GangWorker
    //       - GCTaskThread
    //   - JavaThread
    //   - WatcherThread
    

    其中 JavaThread 继承自 Thread 类。

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    void Thread::start(Thread* thread) {
    trace("start", thread);
    // Start is different from resume in that its safety is guaranteed by context or
    // being called from a Java method synchronized on the Thread object.
    if (!DisableStartThread) {
    if (thread->is_Java_thread()) {
    // Initialize the thread state to RUNNABLE before starting this thread.
    // Can not set it after the thread started because we do not know the
    // exact thread state at that time. It could be in MONITOR_WAIT or
    // in SLEEPING or some other state.
    java_lang_Thread::set_thread_status(((JavaThread*)thread)->threadObj(),
    java_lang_Thread::RUNNABLE);
    }
    os::start_thread(thread);
    }
    }
  • os::start_thread

    jdk7u-hotspot/src/share/vm/runtime/os.cpp

    1
    2
    3
    4
    5
    6
    7
    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);
    }
  • pd_start_thread

    jdk7u-hotspot/src/os/windows/vm/os_windows.cpp

    1
    2
    3
    4
    5
    6
    7
    8
    9
    void os::pd_start_thread(Thread* thread) {
    // ResumeThread 是 win32 sdk 中提供的 API 用来唤醒线程。
    DWORD ret = ResumeThread(thread->osthread()->thread_handle());
    // Returns previous suspend state:
    // 0: Thread was not suspended
    // 1: Thread is running now
    // >1: Thread is still suspended.
    assert(ret != SYS_THREAD_ERROR, "StartThread failed"); // should propagate back
    }
  • osthread 的创建

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    JavaThread::JavaThread(ThreadFunction entry_point, size_t stack_sz) :
    Thread()
    #ifndef SERIALGC
    , _satb_mark_queue(&_satb_mark_queue_set),
    _dirty_card_queue(&_dirty_card_queue_set)
    #endif // !SERIALGC
    {
    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);

    // The _osthread may be NULL here because we ran out of memory (too many threads active).
    // We need to throw and OutOfMemoryError - however we cannot do this here because the caller
    // may hold a lock and all locks must be unlocked before throwing the exception (throwing
    // the exception consists of creating the exception object & initializing it, initialization
    // will leave the VM via a JavaCall and then all locks must be unlocked).
    //
    // The thread is still suspended when we reach here. Thread must be explicit started
    // by creator! Furthermore, the thread must also explicitly be added to the Threads list
    // by calling Threads:add. The reason why this is not done here, is because the thread
    // object must be fully initialized (take a look at JVM_Start)
    }
其中使用到了  os::create_thread 来创建线程。
  • os::create_thread

    jdk7u-hotspot/src/os/windows/vm/os_windows.cpp

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    67
    68
    69
    70
    71
    72
    73
    74
    75
    76
    77
    78
    79
    80
    81
    82
    83
    84
    85
    86
    87
    88
    89
    90
    91
    92
    93
    94
    95
    96
    97
    98
    99
    100
    101
    102
    103
    104
    105
    bool os::create_thread(Thread* thread, ThreadType thr_type, size_t stack_size) {
    unsigned thread_id;

    // Allocate the OSThread object
    OSThread* osthread = new OSThread(NULL, NULL);
    if (osthread == NULL) {
    return false;
    }

    // Initialize support for Java interrupts
    HANDLE interrupt_event = CreateEvent(NULL, true, false, NULL);
    if (interrupt_event == NULL) {
    delete osthread;
    return NULL;
    }
    osthread->set_interrupt_event(interrupt_event);
    osthread->set_interrupted(false);

    thread->set_osthread(osthread);

    if (stack_size == 0) {
    switch (thr_type) {
    case os::java_thread:
    // Java threads use ThreadStackSize which default value can be changed with the flag -Xss
    if (JavaThread::stack_size_at_create() > 0)
    stack_size = JavaThread::stack_size_at_create();
    break;
    case os::compiler_thread:
    if (CompilerThreadStackSize > 0) {
    stack_size = (size_t)(CompilerThreadStackSize * K);
    break;
    } // else fall through:
    // use VMThreadStackSize if CompilerThreadStackSize is not defined
    case os::vm_thread:
    case os::pgc_thread:
    case os::cgc_thread:
    case os::watcher_thread:
    if (VMThreadStackSize > 0) stack_size = (size_t)(VMThreadStackSize * K);
    break;
    }
    }

    // Create the Win32 thread
    //
    // Contrary to what MSDN document says, "stack_size" in _beginthreadex()
    // does not specify stack size. Instead, it specifies the size of
    // initially committed space. The stack size is determined by
    // PE header in the executable. If the committed "stack_size" is larger
    // than default value in the PE header, the stack is rounded up to the
    // nearest multiple of 1MB. For example if the launcher has default
    // stack size of 320k, specifying any size less than 320k does not
    // affect the actual stack size at all, it only affects the initial
    // commitment. On the other hand, specifying 'stack_size' larger than
    // default value may cause significant increase in memory usage, because
    // not only the stack space will be rounded up to MB, but also the
    // entire space is committed upfront.
    //
    // Finally Windows XP added a new flag 'STACK_SIZE_PARAM_IS_A_RESERVATION'
    // for CreateThread() that can treat 'stack_size' as stack size. However we
    // are not supposed to call CreateThread() directly according to MSDN
    // document because JVM uses C runtime library. The good news is that the
    // flag appears to work with _beginthredex() as well.

    #ifndef STACK_SIZE_PARAM_IS_A_RESERVATION
    #define STACK_SIZE_PARAM_IS_A_RESERVATION (0x10000)
    #endif

    HANDLE thread_handle =
    (HANDLE)_beginthreadex(NULL,
    (unsigned)stack_size,
    (unsigned (__stdcall *)(void*)) java_start,
    thread,
    CREATE_SUSPENDED | STACK_SIZE_PARAM_IS_A_RESERVATION,
    &thread_id);
    if (thread_handle == NULL) {
    // perhaps STACK_SIZE_PARAM_IS_A_RESERVATION is not supported, try again
    // without the flag.
    thread_handle =
    (HANDLE)_beginthreadex(NULL,
    (unsigned)stack_size,
    (unsigned (__stdcall *)(void*)) java_start,
    thread,
    CREATE_SUSPENDED,
    &thread_id);
    }
    if (thread_handle == NULL) {
    // Need to clean up stuff we've allocated so far
    CloseHandle(osthread->interrupt_event());
    thread->set_osthread(NULL);
    delete osthread;
    return NULL;
    }

    Atomic::inc_ptr((intptr_t*)&os::win32::_os_thread_count);

    // Store info on the Win32 thread into the OSThread
    osthread->set_thread_handle(thread_handle);
    osthread->set_thread_id(thread_id);

    // Initial thread state is INITIALIZED, not SUSPENDED
    osthread->set_state(INITIALIZED);

    // The thread is returned suspended (in state INITIALIZED), and is started higher up in the call chain
    return true;
    }
其中使用到了 _beginthreadex 来创建 windows 线程。这个函数的使用可以参考:[_beginthreadex](https://msdn.microsoft.com/zh-cn/library/kdzttdcb.aspx)

_beginthreadex 的第5个参数 initflag : Set initflag to 0 to run immediately, or to CREATE_SUSPENDED to create the thread in a suspended state; use ResumeThread to execute the thread.

第三个参数 start_address:表示 Start address of a routine that begins execution of a new thread. 在这里是 java_start 函数。

第四个参数 arglist: 表示 Argument list to be passed to a new thread, or NULL. 就是 java_start 函数的参数,也就就是当前线程对象thread.

这里使用的是 CREATE_SUSPENDED, 所以需要调用 ResumeThread 来,唤醒线程。

关于 OSThread 类:jdk7u-hotspot/src/share/vm/runtime/osThread.cpp。
  • java_start

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    static unsigned __stdcall java_start(Thread* thread) {
    // Try to randomize the cache line index of hot stack frames.
    // This helps when threads of the same stack traces evict each other's
    // cache lines. The threads can be either from the same JVM instance, or
    // from different JVM instances. The benefit is especially true for
    // processors with hyperthreading technology.
    static int counter = 0;
    int pid = os::current_process_id();
    _alloca(((pid ^ counter++) & 7) * 128);

    OSThread* osthr = thread->osthread();
    assert(osthr->get_state() == RUNNABLE, "invalid os thread state");

    if (UseNUMA) {
    int lgrp_id = os::numa_get_group_id();
    if (lgrp_id != -1) {
    thread->set_lgrp_id(lgrp_id);
    }
    }


    if (UseVectoredExceptions) {
    // If we are using vectored exception we don't need to set a SEH
    thread->run();
    }
    else {
    // Install a win32 structured exception handler around every thread created
    // by VM, so VM can genrate error dump when an exception occurred in non-
    // Java thread (e.g. VM thread).
    __try {
    thread->run();
    } __except(topLevelExceptionFilter(
    (_EXCEPTION_POINTERS*)_exception_info())) {
    // Nothing to do.
    }
    }

    // One less thread is executing
    // When the VMThread gets here, the main thread may have already exited
    // which frees the CodeHeap containing the Atomic::add code
    if (thread != VMThread::vm_thread() && VMThread::vm_thread() != NULL) {
    Atomic::dec_ptr((intptr_t*)&os::win32::_os_thread_count);
    }

    return 0;
    }

    创建线程时使用 java_start 是线程的入口函数定义在 os_windows.cpp 中,其最终使用
    thread->run() 来调用 run 方法。 而这里的 thread 就是前面创建的 JavaThread,所以这这里调用的是 JavaThread::run 方法

  • JavaThread::run

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    	// The first routine called by a new Java thread
    void JavaThread::run() {
    // initialize thread-local alloc buffer related fields
    this->initialize_tlab();

    // used to test validitity of stack trace backs
    this->record_base_of_stack_pointer();

    // Record real stack base and size.
    this->record_stack_base_and_size();

    // Initialize thread local storage; set before calling MutexLocker
    this->initialize_thread_local_storage();

    this->create_stack_guard_pages();

    this->cache_global_variables();

    // Thread is now sufficient initialized to be handled by the safepoint code as being
    // in the VM. Change thread state from _thread_new to _thread_in_vm
    ThreadStateTransition::transition_and_fence(this, _thread_new, _thread_in_vm);

    assert(JavaThread::current() == this, "sanity check");
    assert(!Thread::current()->owns_locks(), "sanity check");

    DTRACE_THREAD_PROBE(start, this);

    // This operation might block. We call that after all safepoint checks for a new thread has
    // been completed.
    this->set_active_handles(JNIHandleBlock::allocate_block());

    if (JvmtiExport::should_post_thread_life()) {
    JvmtiExport::post_thread_start(this);
    }

    // We call another function to do the rest so we are sure that the stack addresses used
    // from there will be lower than the stack base just computed
    thread_main_inner();

    // Note, thread is no longer valid at this point!
    }


    void JavaThread::thread_main_inner() {
    assert(JavaThread::current() == this, "sanity check");
    assert(this->threadObj() != NULL, "just checking");

    // Execute thread entry point unless this thread has a pending exception
    // or has been stopped before starting.
    // Note: Due to JVM_StopThread we can have pending exceptions already!
    if (!this->has_pending_exception() &&
    !java_lang_Thread::is_stillborn(this->threadObj())) {
    HandleMark hm(this);
    this->entry_point()(this, this);
    }

    DTRACE_THREAD_PROBE(stop, this);

    this->exit(false);
    delete this;
    }

    JavaThread::run 内部调用 JavaThread::thread_main_inner,然后,
    this->entry_point()(this, this);

    所以,最终上面的 thread_entry 函数的第一个参数将是 JavaThread 这个对象自身。

    注意这里的 this->exit(false); 调用非常重要。这个调用是 JavaThread::exit 方法,在这个方法中调用了一个全局静态函数 ensure_join ,

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    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 调用的注释, allows the join() to complete once we've done the notify_all below。 java.lang.Thread.join 函数就是在这个调用下被 notify, 所以才会被唤醒。
  • JavaThread::entry_point

    这个函数在类 JavaThread 的声明中定义的

    1
    2
    3
    4
    typedef void (*ThreadFunction)(JavaThread*, TRAPS);
    ThreadFunction _entry_point;
    void set_entry_point(ThreadFunction entry_point) { _entry_point = entry_point; }
    ThreadFunction entry_point() const { return _entry_point; }

java_lang_Thread: jdk7u-hotspot/src/share/vm/classfile/javaClasses.cpp

java.lang.Thread.isAlive

1
2
3
4
5
6
7
8
9
10
11
12
13
14
// jdk7u-hotspot/src/share/vm/prims/jvm.cpp
JVM_ENTRY(jboolean, JVM_IsThreadAlive(JNIEnv* env, jobject jthread))
JVMWrapper("JVM_IsThreadAlive");

oop thread_oop = JNIHandles::resolve_non_null(jthread);
return java_lang_Thread::is_alive(thread_oop);
JVM_END

// jdk7u-hotspot/src/share/vm/classfile/javaClasses.cpp
bool java_lang_Thread::is_alive(oop java_thread) {
// 当一个线程退出的时候,会将 thr 设置成 NULL
JavaThread* thr = java_lang_Thread::thread(java_thread);
return (thr != NULL);
}

JavaThread 和 OSThread

JavaThread jni 对 java 线程的抽象。

OSThread 是 对不同平台的线程抽象。

osThread.cpp

osThread_windows.hpp

java 线程启动的启动过程

启动过程中涉及的组件

  • java.lang.Thread

    线程启动函数 start 方法中,调用start0, 由 java 代码转入 JNI 层

  • JNI

    在 JNI 中将该方法实现为 JVM_StartThread,可见 start0 由 JVM 来实现

  • JVM

    调用 JVM_StartThread,创建一个 JavaThread 对象。创建好 JavaThread对象 native_thread 之后 ,调用 JavaThread::prepare 方法。

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    void JavaThread::prepare(jobject jni_thread, ThreadPriority prio) {

    assert(Threads_lock->owner() == Thread::current(), "must have threads lock");
    // Link Java Thread object <-> C++ Thread

    // Get the C++ thread object (an oop) from the JNI handle (a jthread)
    // and put it into a new Handle. The Handle "thread_oop" can then
    // be used to pass the C++ thread object to other methods.

    // Set the Java level thread object (jthread) field of the
    // new thread (a JavaThread *) to C++ thread object using the
    // "thread_oop" handle.

    // Set the thread field (a JavaThread *) of the
    // oop representing the java_lang_Thread to the new thread (a JavaThread *).

    Handle thread_oop(Thread::current(),
    JNIHandles::resolve_non_null(jni_thread));
    assert(instanceKlass::cast(thread_oop->klass())->is_linked(),
    "must be initialized");
    set_threadObj(thread_oop());
    java_lang_Thread::set_thread(thread_oop(), this);

    if (prio == NoPriority) {
    prio = java_lang_Thread::priority(thread_oop());
    assert(prio != NoPriority, "A valid priority should be present");
    }

    // Push the Java priority down to the native thread; needs Threads_lock
    Thread::set_priority(this, prio);

    // Add the new thread to the Threads list and set it in motion.
    // We must have threads lock in order to call Threads::add.
    // It is crucial that we do not block before the thread is
    // added to the Threads list for if a GC happens, then the java_thread oop
    // will not be visited by GC.
    Threads::add(this);
    }
这个方法的主要作用就是:Link Java Thread object <-> C++ Thread

jni_thread 代表的就是,`new Thread()` 后产生的 Java Thread object.
这个参数由 JNI 调用 JVM_StartThread    时的第二个参数。

然后在 prepare 函数中 
`Handle thread_oop(Thread::current(), JNIHandles::resolve_non_null(jni_thread));`
创建一个 thread_oop,通过 set_threadObj(thread_oop()); 调用将
其和 native_thread 关联了起来。

这样 native_thread 内部持有 jni_thread, 所有在后续的线程启动过程中,才可以使用 jni_thread 来更新其 状态信息,例如:threadStatus 字段。

同时在创建 JavaThread的 调用了  os::create_thread 这是给不同平台预留的创建线程的接口:在 windows 平台上使用 os_windows.cpp 中定义的  os::create_thread 方法,其中使用 win32 平台提供的 _beginthreadex 来创建一个线程,创建的线程默认是未启动状态。关键代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
OSThread* osthread = new OSThread(NULL, NULL);
thread->set_osthread(osthread);

HANDLE thread_handle =
(HANDLE)_beginthreadex(NULL,
(unsigned)stack_size,
(unsigned (__stdcall *)(void*)) java_start,
thread,
CREATE_SUSPENDED | STACK_SIZE_PARAM_IS_A_RESERVATION,
&thread_id);

osthread->set_thread_handle(thread_handle);
osthread->set_thread_id(thread_id);
  • JVM Thread 共享层

    这一层,其实就是 Thread 和 JavaThread 类,上面的启动过程,最后调用
    Thread::start(native_thread); 从而转入这一层,这一层对不同平台的线程启动过程进行了封装处理。进行一些公共的初始化操作。之后 调用 os::start_thread 启动线程。

  • 不同平台底层启动中

    在 windows 平台中启动线程。使用 os_windows.cpp 定义的 os::start_thread 开始唤醒线程并执行。

JVM 如果处理线程出现的异常

Thread.UncaughtExceptionHandler

Interface for handlers invoked when a Thread abruptly terminates due to an uncaught exception.

When a thread is about to terminate due to an uncaught exception the Java Virtual Machine will query the thread for its UncaughtExceptionHandler using Thread.getUncaughtExceptionHandler() and will invoke the handler’s uncaughtException method, passing the thread and the exception as arguments. If a thread has not had its UncaughtExceptionHandler explicitly set, then its ThreadGroup object acts as its UncaughtExceptionHandler. If the ThreadGroup object has no special requirements for dealing with the exception, it can forward the invocation to the default uncaught exception handler.

所以对于一个 uncaught exception 的异常,线程的处理过程是:

  • getUncaughtExceptionHandler()

    获得线程的 uncaughtExceptionHandler,然后调用其 uncaughtException 方法

  • getThreadGroup

    获得线程组,调用其 uncaughtException 方法

  • getDefaultUncaughtExceptionHandler

    获得默认的 UncaughtExceptionHandler,调用其 uncaughtException 方法

这个调用过程是由 JavaThread::exit 完成的。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
// JavaThread::exit 实现片断
// JSR-166: change call from from ThreadGroup.uncaughtException to
// java.lang.Thread.dispatchUncaughtException
if (uncaught_exception.not_null()) {
Handle group(this, java_lang_Thread::threadGroup(threadObj()));
Events::log("uncaught exception INTPTR_FORMAT " " INTPTR_FORMAT " " INTPTR_FORMAT",
(address)uncaught_exception(), (address)threadObj(), (address)group());
{
EXCEPTION_MARK;
// Check if the method Thread.dispatchUncaughtException() exists. If so
// call it. Otherwise we have an older library without the JSR-166 changes,
// so call ThreadGroup.uncaughtException()
KlassHandle recvrKlass(THREAD, threadObj->klass());
CallInfo callinfo;
KlassHandle thread_klass(THREAD, SystemDictionary::Thread_klass());
LinkResolver::resolve_virtual_call(callinfo, threadObj, recvrKlass, thread_klass,
vmSymbols::dispatchUncaughtException_name(),
vmSymbols::throwable_void_signature(),
KlassHandle(), false, false, THREAD);
CLEAR_PENDING_EXCEPTION;
methodHandle method = callinfo.selected_method();
if (method.not_null()) {
JavaValue result(T_VOID);
// vmSymbols::dispatchUncaughtException_name
// 对应的就是 Thread.dispatchUncaughtException 这个方法
// 就是用来处理异常分发。
JavaCalls::call_virtual(&result,
threadObj, thread_klass,
vmSymbols::dispatchUncaughtException_name(),
vmSymbols::throwable_void_signature(),
uncaught_exception,
THREAD);
} else {
// vmSymbols::uncaughtException_name() 对应 uncaughtException
// 也就是调用 线程组的 uncaughtException 方法。
KlassHandle thread_group(THREAD, SystemDictionary::ThreadGroup_klass());
JavaValue result(T_VOID);
JavaCalls::call_virtual(&result,
group, thread_group,
vmSymbols::uncaughtException_name(),
vmSymbols::thread_throwable_void_signature(),
threadObj, // Arg 1
uncaught_exception, // Arg 2
THREAD);
}
if (HAS_PENDING_EXCEPTION) {
ResourceMark rm(this);
jio_fprintf(defaultStream::error_stream(),
"\nException: %s thrown from the UncaughtExceptionHandler"
" in thread \"%s\"\n",
Klass::cast(pending_exception()->klass())->external_name(),
get_thread_name());
CLEAR_PENDING_EXCEPTION;
}
}
}

如果线程遇到异常,则 JVM 在 JavaThread::exit 方法将调用 java.lang.Thread.dispatchUncaughtException 方法。这个方法的作用就是进行异常的分发。其分发过程如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
/**
* Dispatch an uncaught exception to the handler. This method is
* intended to be called only by the JVM.
* 这个方法将被 JVM 的 JavaThread:exit 方法调用
*/
private void dispatchUncaughtException(Throwable e) {
getUncaughtExceptionHandler().uncaughtException(this, e);
}

public UncaughtExceptionHandler getUncaughtExceptionHandler() {
return uncaughtExceptionHandler != null ?
uncaughtExceptionHandler : group;
}

public void uncaughtException(Thread t, Throwable e) {
if (parent != null) {
parent.uncaughtException(t, e);
} else {
Thread.UncaughtExceptionHandler ueh =
Thread.getDefaultUncaughtExceptionHandler();
if (ueh != null) {
ueh.uncaughtException(t, e);
} else if (!(e instanceof ThreadDeath)) {
System.err.print("Exception in thread \""
+ t.getName() + "\" ");
e.printStackTrace(System.err);
}
}
}

Java并发相关面试题

Java并发面试题整理

JAVA多线程和并发基础面试问答

Java Native Interface Specification Contents

官方JNI规范[翻译]