Thread Startup Process Analysis and Design Patterns

Posted by mebar3 on Mon, 26 Aug 2019 17:12:24 +0200

As we all know, there are two ways to construct threads in Java. The first way is to inherit the Thread class and override the run method. The second way is to implement the Runnable interface and the run method. But the final boot is started through the start method of the Thread object. So since the logic is written in the run method, why call the start method at startup?

1. Source code parsing of start method of JDK Thread class

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

Looking at the source code, you can see that the method start0 is called in the start method, which is implemented as follows:

private native void start0();

This method is a native method, which is called by JDK through JNI. But when did the run method call?
By looking at the official documents, you can see that the bottom implementation of start0 calls the run method, but only through C++ implementation, interested in the corresponding code can be flipped.

Through the source code of the above start method, the following points can be summarized:

  • (1) When the thread is constructed, a state variable records the state of the thread, that is, threadStatus, whose initial value is 0 declared in the class.
  • (2) After calling the start method to start the thread, the value of threadStatus will be changed. If the start method is called again to start the same thread, an IllegalThreadStateException exception is thrown.
  • (3) thread s are added to a thread group ThreadGroup after they are started.
  • (4) If a thread fails to start, the thread group will handle the thread failure and remove it from the thread group.
  • (5) If a thread's life cycle is over and the start method is called again to start the thread, IllegalThreadStateException will be prompted, that is, threads in TERMINATED state can't return to RUNNABLE or RUNNING state.

Example Verification 1: Verify that threads can start multiple times

Thread thread = new Thread(){
    @Override
    public void run() {
        try {
            TimeUnit.MILLISECONDS.sleep(5);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
};
thread.start();
thread.start();

Running the above code will result in the following exception information:

Exception in thread "main" java.lang.IllegalThreadStateException
at java.lang.Thread.start(Thread.java:705)
at com.wb.spring.test.TestThread.main(TestThread.java:40)

Example Verification 2: The thread life cycle ends and the start method is called again to start

Thread thread = new Thread(){
    @Override
    public void run() {
        try {
            TimeUnit.MILLISECONDS.sleep(1);
            System.out.println("Threads are running!");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
};
// First Start
thread.start();
try {
    TimeUnit.MILLISECONDS.sleep(3);
} catch (Exception e) {
    e.printStackTrace();
}
// Second startup
thread.start();

Running the above sample code will yield the following results:

Threads are running!
Exception in thread "main" java.lang.IllegalThreadStateException
at java.lang.Thread.start(Thread.java:705)
at com.wb.spring.test.TestThread.main(TestThread.java:48)

As you can see from the results, after the thread runs, the life cycle is over and cannot be restarted.

As you can see from the above examples, IllegalThreadStateException exception has been run out, but the two occurrences of this exception are different. The first thread is still alive and its life cycle is not over, but it is not allowed to start repeatedly; the second one is because the thread's life cycle is over, and if you try to start an end thread, the exception will be thrown.

2. Design Patterns in Thread Class-Template Design Patterns

Introduction: Template design pattern refers to the determination of the algorithm structure in the inheritance structure in the parent class, while the specific implementation details of the algorithm are given to the subclass to complete. For example, the source code of the run method in the Thread class is as follows. If the Thread class is used to construct threads, the run method is equivalent to an empty implementation, but when the start method is called, the implementation details of the sub-class run method can be correctly executed.

@Override
public void run() {
    if (target != null) {
        target.run();
    }
}

This design pattern is helpful for the parent class to determine the structure of the program.
Examples of template design patterns:

public class TemplateTest {
    public final void say(String msg) {
        System.out.println("000000");
        sayHello(msg);
        System.out.println("000000");
    }

    protected void sayHello(String msg) {
        
    }

    public static void main(String[] args) {
        TemplateTest test1 = new TemplateTest() {
            @Override
            protected void sayHello(String msg) {
                System.out.println("***" + msg + "***");
            }
        };
        test1.say("wb");
        TemplateTest test2 = new TemplateTest() {
            @Override
            protected void sayHello(String msg) {
                System.out.println("&&&" + msg + "&&&");
            }
        };
        test2.say("bw");
    }
}

The input results are as follows:

000000
***wb***
000000
000000
&&&bw&&&
000000

As you can see, what symbols need to be input can be freely controlled by subclasses! This is the benefit of template design patterns!

This is the Thread class to start the process of threads and the use of design patterns in detail. Comments are welcome to be forwarded.
Also provide some free IT video materials, architects, high availability, high concurrency and other tutorials! Check it out if you need to https://www.592xuexi.com

Topics: Java JDK Spring