Detailed explanation of Java thread life cycle

foreword

The thread life cycle in Java is the core concept of multi-threaded development. Understanding the lifecycle of threads and how they undergo state transitions is critical to writing efficient and error-free multithreaded programs.

1. Thread life cycle

Java threads mainly have the following states, which are defined in the Thread.State enumeration class:

  1. New state (New) : When we create a new thread instance, the thread is in the new state. At this time, start()the method of the thread has not been called, and the execution of the thread object has not yet started. In this state, the Java Virtual Machine (JVM) has allocated the necessary memory for this thread.

    Thread t = new Thread(); // 线程此时处于New状态
    
  2. Ready state (Runnable) : When the thread object calls start()the method, the thread is in the ready state. A thread in the ready state can start running after obtaining a CPU time slice. The thread in this state is located in the runnable thread pool, waiting to be selected by thread scheduling to obtain the right to use the CPU.

    t.start(); // 线程此时处于Runnable状态
    
  3. Running state (Running) : After the thread obtains the CPU time slice, it enters the running state and starts to execute run()the code in the method. It is worth noting that the actual speed and efficiency of code execution is related to the speed of the processor and the number of cores in a multi-core processor.

    public void run() {
          
          
        System.out.println("Thread is running.");
    }
    // 如果此时这个方法正在执行,那么线程就处于Running状态
    
  4. Blocked state (Blocked) : When a thread tries to acquire an internal object lock (that is, enter a synchronizedblock), and the lock is held by other threads, the thread enters the blocked state. A thread in the blocked state will enter the ready state when the lock is released.

    synchronized(object) {
          
          
        // 如果此时object的锁被其他线程持有,那么线程就处于Blocked状态
    }
    
  5. Waiting : A thread can enter the waiting state by calling its own wait()method, join()method, or LockSupport.park()method, or by calling a method of another thread . join()Threads in the waiting state are not allocated CPU time slices, they can only enter the ready state by being explicitly woken up by other threads.

    t.wait();  // 线程此时处于Waiting状态
    t.join();  // 线程此时处于Waiting状态
    
  6. Timed Waiting state (Timed Waiting) : When a thread calls sleep(long ms), wait(long ms), join(long ms), or LockSupport.parkNanos(), LockSupport.parkUntil()etc. a method with a specified waiting time, the thread will enter the timed waiting state. When the timeout expires, the thread automatically returns to the ready state.

    Thread.sleep(1000); // 线程此时处于Timed Waiting状态
    
  7. Terminated state : When run()the method of the thread is executed, or the thread is interrupted, the thread will enter the terminated state. In this state, the thread has completed all of its work.

    // 当run()方法执行完毕,线程处于Terminated状态
    public void run() {
          
          
        System.out.println("Thread is running.");
    }
    

The transition between these states is realized by calling various methods. Next we will see the details of these state transitions.

2. Thread state transition

insert image description here

The transition of thread state is a very important part. Understanding the transition between states helps us better understand and master the behavior of threads. Next, let's take a look at the transitions of various thread states in Java.

  1. New state to ready state : When the thread object is created, it enters the new state. At this time, by calling start()the method of the thread object, the thread can enter the ready state and wait for the thread scheduler of the system to schedule.

    Thread t = new Thread(); // 新建状态
    t.start(); // 调用start()方法,线程进入就绪状态
    
  2. Ready state to running state : The thread scheduler selects a thread from the ready queue and allocates CPU resources to it, and the thread changes from the ready state to the running state.

  3. The running state changes to the ready state : when a thread in the running state calls yield()a method, or the running time of the thread exceeds the time slice specified by the system, the thread will release CPU resources, change itself from the running state to the ready state, and wait for the system to schedule again .

    Thread.yield(); // 调用yield()方法,线程从运行状态进入就绪状态
    
  4. Running state to blocked state : When a thread in the running state tries to acquire an object lock held by other threads, the thread will enter the blocked state.

    synchronized(object) {
          
          
        // 如果此时object的锁被其他线程持有,那么线程就从运行状态进入阻塞状态
    }
    
  5. Blocked state to ready state : When a thread in the blocked state acquires the object lock released by other threads, the thread changes from the blocked state to the ready state and waits for the system to schedule again.

  6. Running state to waiting state : When a thread in the running state calls wait()the join()or LockSupport.park()method, the thread will enter the waiting state. Threads in the waiting state need to rely on notifications from other threads to return to the ready state.

    t.wait(); // 调用wait()方法,线程从运行状态进入等待状态
    t.join(); // 调用join()方法,线程从运行状态进入等待状态
    
  7. Waiting state to ready state : When a thread in the waiting state is called notify()or notifyAll()awakened by other threads, or is interrupted by other threads, or the waiting time expires, the thread changes from the waiting state to the ready state.

    t.notify(); // notify()方法被调用,线程从等待状态进入就绪状态
    
  8. The running state changes to the timeout waiting state : when a thread in the running state calls the sleep(), wait(), join(), or method with a timeout parameter, the thread will enter the timeout waiting state.LockSupport.parkNanos()LockSupport.parkUntil()

    Thread.sleep(1000); // 调用sleep()方法,线程从运行状态进入超时等待状态
    
  9. Timeout waiting state to ready state : When the waiting time of a thread in the timeout waiting state expires, or is woken up or interrupted by other threads, the thread will change from the timeout waiting state to the ready state.

  10. Any state to terminated state : When a thread completes its task or exits due to an exception, it enters the terminated state.

By understanding the state transitions of the above threads, you can gain a deeper understanding of the operating mechanism of threads and provide a theoretical basis for multi-threaded programming.

3. Example of thread life cycle

The following Java code example demonstrates the entire process of a thread from creation to termination:

// 创建一个继承了Thread类的ExampleThread类
class ExampleThread extends Thread {
    
    
    private Object lock; // 创建一个私有的Object对象,它将在同步代码块中被使用作为锁

    // 构造函数,接受一个Object类型的参数
    public ExampleThread(Object lock) {
    
    
        this.lock = lock; // 将传入的对象赋值给lock
    }

    // 重写Thread类的run方法
    @Override
    public void run() {
    
    
        // 同步代码块,只有获取到lock对象的锁才能执行
        synchronized(lock) {
    
    
            try {
    
    
                // 输出线程名和状态
                System.out.println(Thread.currentThread().getName() + " is running");
                // 让线程睡眠1秒,此时线程进入TIMED_WAITING状态
                Thread.sleep(1000);

                // 输出线程名和状态
                System.out.println(Thread.currentThread().getName() + " is waiting");
                // 调用wait()方法,线程释放lock锁,进入WAITING状态
                lock.wait();

                // 线程被唤醒,获取到lock锁,输出线程名和状态
                System.out.println(Thread.currentThread().getName() + " is running again");
            } catch (InterruptedException e) {
    
    
                // 线程被中断,输出线程名和状态,然后线程将结束
                System.out.println(Thread.currentThread().getName() + " is interrupted and will terminate");
            }
        }
    }
}

public class Main {
    
    
    public static void main(String[] args) throws InterruptedException {
    
    
        // 创建一个共享的锁对象
        Object lock = new Object();

        // 创建一个新的线程(NEW状态)
        Thread t1 = new ExampleThread(lock);
        System.out.println(t1.getName() + " is created");

        // 启动新的线程(READY/RUNNABLE状态)
        t1.start();

        // 让主线程睡眠2秒,这样新线程就可以先运行
        Thread.sleep(2000);

        // 唤醒等待的线程(将进入READY/RUNNABLE状态)
        synchronized(lock) {
    
    
            lock.notify();
        }

        // 让主线程再睡眠1秒,这样被唤醒的线程可以完成运行
        Thread.sleep(1000);
    }
}

This code example demonstrates the entire process of a Java thread from being created (NEW state), to being ready and running (READY/RUNNABLE state), to waiting (WAITING state), being woken up and running again, and finally terminated (TERMINATED state).
to optimize application performance.

conclusion

I hope the above content can help you understand the life cycle of Java threads. Understanding the thread life cycle is very important for writing concurrent programs and for multithreaded programming. Remember, the best way to learn is by doing. Therefore, I encourage you to try the above code yourself to gain a deeper understanding of each stage of the thread life cycle.

Guess you like

Origin blog.csdn.net/weixin_46703995/article/details/131263544