[JavaSE Column 76] Three-state and five-state, different states of threads: new, running, state, blocking, waiting, timing waiting state

Author Homepage: Designer Xiaozheng
About the author: 3 years of JAVA full-stack development experience, focusing on JAVA technology, system customization, remote guidance, dedicated to enterprise digital transformation, certified lecturer of CSDN College and Blue Bridge Cloud Course.
Main direction: Vue, SpringBoot, WeChat applet

This article explains the concepts of three states and five states in Java, introduces the application scenarios of new, running, status, blocking, waiting, and timing waiting states, and gives sample codes. Three-state/five-state is a simplified description, in reality threads may transition between different states.

Table of Contents

  • 1. What is a three-state
  • 2. What are the five states
  • How to change between the three and five states
    • 3.1 Transition from the new state to the running state
    • 3.2 Transition from running state to blocking state
    • 3.3 Transition from running state to waiting state
    • 3.4 Transition from running state to timing waiting state
    • 3.5 Transition from running state to terminated state
  • Application scenarios of four and five states
  • Five, JAVA five state interview questions
  • 6. Summary

1. What is tri-state

In Java multi-thread programming, three-state refers to the three states of threads, including the following three states, please study carefully.

  1. New state: When instantiating the Thread class or creating an implementation class object of the Runnable interface, the thread is in the newly created state. At this point the thread object is created, but the start() method has not been called to start the thread.
  2. Running state: When the thread object calls the start() method, the thread enters the running state. At this point the thread executes the code in its run() method. In the running state, the thread may be preempted by the operating system, or it may actively give up the execution right of the CPU.
  3. Blocked state: When the thread is running, it may temporarily be unable to continue execution due to some reasons, and enters the blocked state. Common reasons for blocking include waiting for I/O operations, waiting to acquire locks, and so on. In the blocked state, the thread suspends execution until the cause of the blocking is removed.

In addition, there is a special status, please pay attention to it.

  • Termination status: When the thread’s run() method is executed or the Thread class’ stop() method is called After that, the thread enters the terminated state, and the thread in the terminated state no longer has the ability to run and block, it is called death.

Three-state is a simplified description, in reality threads may transition between different states. For example, when a thread in the running state calls the sleep() method, it will enter the blocked state; when the waiting I/O operation is completed, the blocked thread will enter the running state again. The transition of the thread state is automatically managed by the operating system and the Java runtime environment, and developers can control the state transition of the thread by calling the method of the thread.

2. What are the five states

In Java multithreaded programming, the five states include the following

5

5

5 states, please study carefully.

  1. New state: When instantiating the Thread class or creating an implementation class object of the Runnable interface, the thread is in the newly created state. At this point the thread object is created, but the start() method has not been called to start the thread.
  2. Running state: When the thread object calls the start() method, the thread enters the running state. At this point the thread executes the code in its run() method. In the running state, the thread may be preempted by the operating system, or it may voluntarily give up the execution right of CPU.
  3. Blocked state: When the thread is running, it may temporarily be unable to continue execution due to some reasons, and enters the blocked state. Common blocking reasons include waiting for I/O operations, waiting to acquire locks, and so on. In the blocked state, the thread suspends execution until the cause of the blocking is removed.
  4. Waiting state: The thread enters the waiting state because some waiting methods are called, such as calling the wait() method of the Object class or the Thread class The join() method. In the waiting state, the thread will suspend execution and release the occupied lock resource until it is woken up by other threads.
  5. Timing waiting state: The thread enters the timing waiting state because some timing waiting methods are called, such as the sleep() method of the Thread class is called Or the wait(long timeout) method of the Object class. Similar to the waiting state, the thread will suspend execution and release the occupied lock resources, but it will automatically wake up after the specified time.

The above five states are descriptions of ordinary threads. For Daemon threads, there is a special state:

  • Terminated state: When the run() method of the thread is executed or the stop() method of the Thread class is called, the thread enters the termination state state, a thread in the terminated state no longer has the ability to run and block, it is called dead.

Thread state transitions are automatically managed by the operating system and JVM, and developers can control thread state transitions by calling thread methods.

3. How to change between the five states

In Java, the state of a thread is automatically managed by the JVM and the operating system, and developers cannot directly control state transitions.

However, we can trigger state transitions by calling different methods of threads. The following are some common transition examples between thread states, please study carefully.

  1. New State -> Running State: Start the thread by calling the start() method of the thread object, and the thread will change from the new state to the running state.
  2. Running state-> Blocking state: The thread may be waiting for I/O operations, waiting to acquire locks, or calling Thread The sleep() method and other reasons enter the blocking state.
  3. Running state -> Waiting state: The thread calls the wait() method of the Object class, or the Thread class The join() method waits for the completion of other threads and enters the waiting state.
  4. Running state-> Timing waiting state: The thread calls the sleep(long millis) method of the Thread class, or the of the **Object** class wait(long timeout)` method, the thread will automatically wake up after the specified time and enter the timing waiting state.
  5. Running state-> Termination state: The run() method of the thread is executed, or the stop()< of the Thread class is called /code> method, the thread enters the terminated state.

Thread state transitions are managed by the JVM and the operating system, and developers cannot directly control and predict thread state transitions. Therefore, when writing multi-threaded programs, students need to correctly handle the state transition of threads to avoid potential concurrency problems and deadlocks.

The following are some sample codes for the five-state transition of Java threads, please copy and execute them locally.

3.1 Transition from new state to running state

Thread thread = new Thread(() -> {<!-- -->
    // tasks to be executed by the thread
});
thread.start(); // Start the thread, the thread transitions from the new state to the running state

3.2 Transition from running state to blocking state

public class MyRunnable implements Runnable {<!-- -->
    private Object lock;

    public MyRunnable(Object lock) {<!-- -->
        this. lock = lock;
    }

    @Override
    public void run() {<!-- -->
        synchronized (lock) {<!-- -->
            // critical section code
            try {<!-- -->
                Thread.sleep(1000); // The thread sleeps and enters the blocked state
            } catch (InterruptedException e) {<!-- -->
                e.printStackTrace();
            }
        }
    }
}

public class Main {<!-- -->
    public static void main(String[] args) {<!-- -->
        Object lock = new Object();
        Thread thread1 = new Thread(new MyRunnable(lock));
        Thread thread2 = new Thread(new MyRunnable(lock));
        thread1. start();
        thread2.start();
    }
}

3.3 Transition from running state to waiting state

public class MyRunnable implements Runnable {<!-- -->
    private Object lock;

    public MyRunnable(Object lock) {<!-- -->
        this. lock = lock;
    }

    @Override
    public void run() {<!-- -->
        synchronized (lock) {<!-- -->
            try {<!-- -->
                lock.wait(); // thread enters waiting state
            } catch (InterruptedException e) {<!-- -->
                e.printStackTrace();
            }
        }
    }
}

public class Main {<!-- -->
    public static void main(String[] args) {<!-- -->
        Object lock = new Object();
        Thread thread = new Thread(new MyRunnable(lock));
        thread. start();
    }
}

3.4 Transition from running state to timing waiting state

public class MyRunnable implements Runnable {<!-- -->
    @Override
    public void run() {<!-- -->
        try {<!-- -->
            Thread.sleep(2000); // The thread sleeps and enters the timing waiting state
        } catch (InterruptedException e) {<!-- -->
            e.printStackTrace();
        }
    }
}

public class Main {<!-- -->
    public static void main(String[] args) {<!-- -->
        Thread thread = new Thread(new MyRunnable());
        thread. start();
    }
}

3.5 Transition from running state to terminated state

public class MyRunnable implements Runnable {<!-- -->
    @Override
    public void run() {<!-- -->
        // tasks to be executed by the thread
    }
}

public class Main {<!-- -->
    public static void main(String[] args) {<!-- -->
        Thread thread = new Thread(new MyRunnable());
        thread. start();
        // Wait for the thread to finish executing, and the thread transitions from the running state to the terminated state
        try {<!-- -->
            thread. join();
        } catch (InterruptedException e) {<!-- -->
            e.printStackTrace();
        }
    }
}

The above are sample codes of some common Java thread five-state transitions, which implement transitions between states by triggering different methods or operations. In practical applications, students need to flexibly use different states of threads according to specific needs and situations to achieve the goal of concurrent programming.

4. Application scenarios of five states

The five states of threads in Java can play a role in different application scenarios. The following are some common application scenarios, please study carefully.

  1. New state: The state after the thread object is created but before the start() method is called. This state is suitable for thread preparation, such as allocating resources for threads, initializing variables, and so on.
  2. Running state: The state entered after the thread is started, the thread is executing the tasks in the run() method. In concurrent programming, multiple running threads can be used to perform different tasks at the same time, improving the throughput and responsiveness of the system.
  3. Blocked state: The thread cannot execute for some reason and enters the blocked state. This state is suitable for waiting for external resources, waiting for locks, or waiting for other threads to complete some operations. For example, when a thread needs to access a shared resource, if the resource is already occupied by other threads, the current thread will enter a blocked state until the resource is released.
  4. Waiting state: The thread calls the wait() method of the Object class or the join() method of the Thread class to enter the waiting state. This state is suitable for coordination and communication between threads. For example, a thread waits for other threads to complete some operations before proceeding.
  5. Timing waiting state: The thread calls the sleep(long millis) method of the Thread class or the wait(long timeout) method of the Object class, and enters the timing waiting state. This state is suitable for scenarios where you want the thread to pause for a period of time before continuing to execute.

The flexible conversion and reasonable use of these states can realize the cooperation between threads, the sharing and utilization of resources, and improve the concurrent performance and response speed of the program. But it should be noted that for multi-threaded programming, thread safety and synchronization issues need to be paid attention to to avoid uncertain results and race conditions.

5. JAVA five-state interview questions

  1. Please explain what are the five states of a thread in Java?
  2. How to transition a thread from new state to running state in Java?
  3. Under what circumstances will a thread change from a running state to a blocked state?
  4. What are wait states and timed wait states? What's the difference between them?
  5. How to transition a thread from running state to waiting state or timed waiting state?
  6. How to transition a thread from waiting state or timed waiting state to running state?
  7. Under what circumstances will a thread transition from the running state to the terminated state?
  8. In Java, how to properly handle state transitions of threads to avoid potential concurrency issues?

6. Summary

This article explains the concepts of three-state and five-state in Java, introduces the application scenarios of new, running, status, blocking, waiting, and timing waiting states, and gives sample codes. In the next blog, I will explain how Java Implement thread creation and startup.

syntaxbug.com © 2021 All Rights Reserved.