Java thread basis - recognize and distinguish Thread ThreadLocal ThreadGroup (a)

    Thread, ThreadLocal and Java ThreadGroup is thread-related knowledge, why this topic is open because ThreadGroup this thing appears in the last chapter, we want him to learn and to practice the practical application scenarios.

1.Thread

1.1 Description Thread

  Thread is the thread, the thread I think we can explain from outside to inside, outside is is a computer, we want to use our computers, most people are to have a basic operating system, such as windows, linux, macos, we operate through watch video systems, micro-letters, in fact, can be seen watching the video and called on the micro-channel two application tasks, operating system, CPU scheduling tasks are performed by, let's look can watch the video at the same time keep up with micro-letters, a task is a process, the thread is the process of sub-units, the equivalent of you watch the video with video software is a thread, you send video comment video software is a thread, you can watch the video at the same time in the same software with a video comment.
    In Java, a Java program opens a JVM process, which JVM is a virtual computer simulation run by the computer software technology. We all know that Java programs need to go through the compiler, generating .Class bytecode files, JVM in order to identify and run it, JVM JVM for each operating system to develop its corresponding interpreter, so long as they have the corresponding version of the operating system, the code then the Java compiler can be up and running, which is a Java compiler can cause running everywhere.
    JVM structure as shown below

JVM thread shares: heap, the method area
JVM thread exclusive areas: virtual machine stack, native method stacks, program counter

1.2 Thread underlying operating

In Java, we use the Java-based application program Thread explained.

             log("主线程执行开始");
               new Thread(() -> {
                   try{
                       Thread.sleep(300);
                   }catch (InterruptedException  e){
                       e.printStackTrace();
                   }
                   log("运行任务1结束...");
               }).start();
               new Thread(() -> {
                   try{
                          Thread.sleep(200);
                       }catch (InterruptedException  e){
                           e.printStackTrace();
                       }
                   log("运行任务2结束...");
               }).start();
               log("主线程结束");


Console output results are as follows:
Here Insert Picture Description

  The above procedure is the main thread, started with two sub-thread Task 1 Task 2, Task 1 main dormant 300ms, Task 2 sleep 200ms, the output from the console of view, the end of the main thread does not affect the child threads 1, 2 implementation, each sub-thread execution is not a series of independent execution in a Java program, multi-threaded applications is very wide to let java program faster processing task to achieve customer needs.

1.3 Thread start principle

1.3.1 thread.start () start the thread

& Nbsp & nbsp start a Thread is through the method of triggering Thread.start () of
Here Insert Picture Description

Really started when the thread start0 () This method, before the thread is put ThreadGroup, that is we will be talking about here is not elaborate. After the start is a change in state of the thread.
start0 defined as follows:

    private native void start0();

1.3.2 Creating underlying thread objects

A Native Method is a non-call interface java java code. A Native Method is a method java: implementing the method is implemented by a non java language, such as C. static method at the time of the start and created Thread, registerNatives ()
Here Insert Picture Description

The local method registerNatives is defined in the Thread.c file. Thread.c is a small file that defines the common thread of data and operations on various operating system platforms to be used, as follows:

JNIEXPORT void JNICALL Java_java_lang_Thread_registerNatives(JNIEnv *env, jclass cls)
{
    (*env)->RegisterNatives(env, cls, methods, ARRAY_LENGTH(methods));
}
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},
};

Thread.java source
http://hg.openjdk.java.net/jdk6/jdk6/jdk/file/a049121b193b/src/share/classes/java/lang/Thread.java

Start0 find the corresponding call JVM_StartThread, call JVM_StartThread, extracting the core to achieve the following:

JVM_ENTRY(void, JVM_StartThread(JNIEnv* env, jobject jthread))
  JVMWrapper("JVM_StartThread");
      //省略
      native_thread = new JavaThread(&thread_entry, sz);
      //省略
    }
  }

JVM_StartThread creation steps:

1.申请一个锁 创建一个JavaThread对象如果有异常情况,抛出异常
2.对第二步的JavaThread类,做一个准备操作:thread.cpp$JavaThread::prepare
3.调用Thread::start方法,让一条线程开始运行

jvm.cpp代码来源
http://hg.openjdk.java.net/jdk7/jdk7/hotspot/file/tip/src/share/vm/prims/jvm.cpp

JVM_StartThread中创建了一个JavaThread对象,
抽取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
{
 
  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);

}

thread.cpp代码来源
http://hg.openjdk.java.net/jdk8u/jdk8u/hotspot/file/cf85f331361b/src/share/vm/runtime/thread.cpp#l1566

可以看到JavaThread里面创建了OSThread,OSThread是一个平台相关线程,OSThread由JavaThread对象创建并进行管理。在OSThread创建的过程中,会通过pthread方法来创建一个真正意义上的底层级线程。

1.3.3 运行线程

pthread.create the new thread will be created () run from thread_native_entry, thread_native_entry called thread- () in> run (), run () which calls thread_main_inner ()> entry_point () (this, this), entry_point () return is actually passed in the new JavaThread (& thread_entry, sz) thread_entry. Here is equivalent to calling the thread_entry (this, this). thread_entry defined in jvm.cpp in:


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

jvm.cpp Source Code
http://hg.openjdk.java.net/jdk7/jdk7/hotspot/file/tip/src/share/vm/prims/jvm.cpp

The above text may very flowing water, is probably to describe that direction, you can refer to the jump. The core is the above code snippet JavaCall, this method is to call run Java thread object () method, and ran away.

Above is how we start a thread running process.

1.4 Thread understand

We believe that through awareness Thread on the face of explanation, we can probably know more or less what threads he is, he is doing what he is doing and how the relevant principles, the next chapter will be on the basis of the understanding of the Thread ThreadGroup learning.

Published 23 original articles · won praise 22 · views 6917

Guess you like

Origin blog.csdn.net/qq_28540443/article/details/104578493