Thread source code analysis


It was written yesterday:

If you haven't read it, please read it first~

Before writing the article, I read through the concurrency chapter of "Java Core Technology Volume 1" and the previous part of "Java Concurrent Programming Practice", and reviewed the notes written before. From today, I will enter the knowledge point of multi-threading~

In fact, I am also equivalent to learning multithreading from scratch. If there are mistakes in the article, please include more, and feel free to correct me in the comment area~~

1. Thread thread class API

Statement that this article uses JDK1.8

The realization of multi-threading is essentially operated by the Thread class. Let's take a look at some important knowledge points of the Thread class . The Thread class is very large, and it is impossible to look at it in its entirety, only some common and important methods .

We have already parsed the comments at the top. If you don’t know, you can go to: Multi-threading can be done in three minutes!

1.1 Set the thread name

When we use multi-threading, it is very simple to check the thread name, just call Thread.currentThread().getName().

If there is no setting for what to do, we will find that the names of the threads are like this: the main thread is called main, and the other threads are Thread-x

Here I will take you to see how it is named:



nextThreadNum()The method implementation is like this:



Based on such a variable --> the number of thread initializations



Click in and see the init method to be sure:


Seeing here, if we want to give the thread a name, it is also very simple. Thread provides us with a constructor !



Let's test it:

  • Implemented the Runnable way to achieve multi-threading:

public class MyThread implements Runnable {
    public void run() {
		// 打印出当前线程的名字


public class MyThreadDemo {
    public static void main(String[] args) {

        MyThread myThread = new MyThread();

        Thread thread1 = new Thread(myThread, "关注公众号Java3y");
        Thread thread2 = new Thread(myThread, "qq群:742919422");

		// 打印当前线程的名字




Of course, we can also setName(String name)change the name of the thread through the method. Let's take a look at the method implementation;



Check if you have permission to modify:



As for the status attribute of threadStatus, I don't seem to find where he will modify it :



1.2 Daemon threads

Daemon threads serve other threads

  • The garbage collection thread is the daemon thread ~

Daemon threads have a feature :

  • When other user threads finish executing, the virtual machine will exit and the daemon thread will be stopped.
  • That is to say: the daemon thread is a service thread, and there is no need to continue running without a service object .

Things to keep in mind when using threads

  1. Set as a daemon thread before the thread starts , bysetDaemon(boolean on)
  2. Do not access shared resources (databases, files, etc.) with a daemon thread , as it may hang at any time.
  3. A new thread spawned in a daemon thread is also a daemon thread

Test a wave:

public class MyThreadDemo {
    public static void main(String[] args) {

        MyThread myThread = new MyThread();

        Thread thread1 = new Thread(myThread, "关注公众号Java3y");
        Thread thread2 = new Thread(myThread, "qq群:742919422");

        // 设置为守护线程


The above code can be run many times (students with good computer performance may not be able to test it): After thread 1 and the main thread are executed, our daemon thread will not be executed ~



Principle: That's why we need to set up the daemon thread before starting it .



1.3 Priority threads

A high thread priority simply means that the thread has a high chance of getting a CPU time slice , but it's not a deterministic factor !

The priority of the thread is highly dependent on the operating system , Windows and Linux are different (the priority may be ignored under Linux)~

As you can see, the priority provided by Java is 5 by default, the lowest is 1, and the highest is 10:






setPriority0is a native method:

 private native void setPriority0(int newPriority);

1.4 Thread life cycle

In the previous introduction, it was also mentioned that the thread of the thread has 3 basic states: execution, ready, blocked

In Java, we have this picture. Many methods on Thread are used to switch the state of the thread. This part is the key point!



In fact, the above picture is not complete enough, and some things are omitted . I will draw a new one when I explain the thread state later~

The following will explain the methods related to the thread life cycle~

1.4.1sleep method

Calling the sleep method will enter the timing waiting state. When the time is up, it will enter the ready state instead of the running state !



Therefore, our diagram can be supplemented as follows:



1.4.2yield method

Calling the yield method will let other threads execute first , but it does not ensure that it actually yields

  • It means: I am free, if possible, let you execute first



Therefore, our diagram can be supplemented as follows:



1.4.3 join method

Calling the join method will wait for the thread to finish executing before executing other threads ~



Let's go in and see the specific implementation :



The wait method is defined on Object, it is a native method, so it can't be seen:



The wait method is actually a kind of **timed wait (if it has a time parameter)**! , so we can supplement our graph:



1.4.3interrupt method

Thread interruption had a stop method in previous versions, but it was set obsolete. There is no way to force a thread to terminate now !

Because the stop method allows one thread A to terminate another thread B

  • The terminated thread B releases the lock immediately, which may leave the object in an inconsistent state .
  • Thread A does not know when thread B can be terminated . If thread B is still processing the running calculation phase, thread A calls the stop method to terminate thread B, which is very innocent~

All in all, the Stop method is too brute force and insecure, so it is set obsolete.

We generally use interrupt to request to terminate the thread ~

  • A word of caution: interrupt doesn't actually stop a thread, it just signals the thread that it should end (very important to understand!)
  • That is to say: Java designers actually want the thread to terminate itself , and through the above signal , you can determine what business to handle.
  • Specifically, whether to interrupt or continue to run should be handled by the notified thread itself.

Thread t1 = new Thread( new Runnable(){
    public void run(){
        // 若未发生中断,就正常执行任务
            // 正常任务代码……
        // 中断的处理代码……
} ).start();

Again: calling interrupt() does not really terminate the current thread , it just sets an interrupt flag. This interrupt flag can be used for us to determine when to do what work ! It's up to us to decide when to interrupt , so it's safe to terminate the thread!

Let's take a look at what the source code says:



Let's take a look at what the exception was thrown just now:



So: the interrupt method will not affect the state of the thread at all, it only sets a flag bit.

There are two other ways to interrupt thread interruption (check if the thread is interrupted) :

  • The static method interrupted()--> will clear the interrupt flag bit
  • The instance method isInterrupted()--> will not clear the interrupt flag bit





As mentioned above, if the blocking thread calls the interrupt() method, an exception will be thrown, the flag will be set to false, and the thread will exit the blocking. Let's test a wave:

public class Main {
     * @param args
    public static void main(String[] args) {
        Main main = new Main();

        // 创建线程并启动
        Thread t = new Thread(main.runnable);
        System.out.println("This is main ");

        try {

            // 在 main线程睡个3秒钟
        } catch (InterruptedException e) {
            System.out.println("In main");

        // 设置中断

    Runnable runnable = () -> {
        int i = 0;
        try {
            while (i < 1000) {

                // 睡个半秒钟我们再执行

        } catch (InterruptedException e) {

            // 判断该阻塞线程是否还在

            // 判断该线程的中断标志位状态

            System.out.println("In Runnable");




Next, we analyze how its execution process is:



April 18, 2018 20:32:15 (wow, this method really consumes me for a very long time).....Thanks to @startde trace for the advice~~~~~

This reference:

2. Summary

It can be found that our graph has not been completed yet~ Subsequent articles will continue to use the above graph when it comes to synchronization. The important thing in Thread is the methods that can switch the thread state , as well as understanding the real meaning of interrupt.

Using threads will cause our data to be unsafe, and even the program cannot run. These problems will be explained later~

When I was learning the operating system before, I also took some notes based on the book "Computer Operating System - Tang Xiaodan", which are relatively simple knowledge points . Maybe it helps everyone


  • "Java Core Technology Volume 1"
  • "Java Concurrent Programming Practice"
  • "Computer Operating System - Tang Xiaodan"

If there are any mistakes in the article, please correct me, and we can communicate with each other. Students who are used to reading technical articles on WeChat and want to get more Java resources can follow WeChat public account: Java3y .

Table of Contents Navigation for Articles :



Guess you like