Home  >  Article  >  Java  >  In-depth study of several states of Java threads and their impact on program execution

In-depth study of several states of Java threads and their impact on program execution

PHPz
PHPzOriginal
2024-02-21 23:27:041034browse

In-depth study of several states of Java threads and their impact on program execution

In-depth study of several states of Java threads and their impact on program execution

In Java, a thread is a lightweight execution unit that can be Programs run independently and perform specific tasks. The status of a thread describes the different stages of a thread's execution. Understanding the status of a thread is very important for writing multi-threaded programs and optimizing program performance. This article will delve into several states of Java threads and their impact on program execution, and provide specific code examples.

The several states of Java threads include: NEW (new), RUNNABLE (runnable), BLOCKED (blocked), WAITING (waiting), TIMED_WAITING (timed waiting) and TERMINATED (terminated).

  1. New (NEW) state: When a new thread is created by creating an instance of the Thread class, the thread is in the new state. In the new state, the thread has not yet started running any code. The following is a sample code for creating a new thread:
Thread thread = new Thread(() -> {
    System.out.println("Hello, World!");
});
  1. Runnable (RUNNABLE) state: When the thread calls the start() method, the thread will enter the runnable state. In this state, the thread will wait for the CPU to allocate a time slice in order to execute the code in the run() method. If there are multiple threads in a runnable state, the operating system will allocate time slices to these threads according to the scheduling policy. The following is a sample code:
Thread thread = new Thread(() -> {
    System.out.println("Hello, World!");
});
thread.start();
  1. Blocked (BLOCKED) state: When the thread cannot continue to execute for some reason, the thread will enter the blocking state. Common reasons include waiting for locks, waiting for input and output (I/O), etc. In the blocking state, the thread suspends execution until a certain condition is met before it can continue execution. Here is a sample code that uses the synchronized keyword to achieve thread synchronization:
public class MyRunnable implements Runnable {
    private Object lock = new Object();
    
    public void run() {
        synchronized(lock) {
            System.out.println("In synchronized block");
            // 一些代码
        }
    }
  
    public static void main(String[] args) {
        MyRunnable runnable = new MyRunnable();
        Thread thread1 = new Thread(runnable);
        Thread thread2 = new Thread(runnable);
  
        thread1.start();
        thread2.start();
    }
}

In the above code, two threads try to enter the synchronized block at the same time, because the lock is shared, the second thread It will enter a blocking state until the first thread completes execution and releases the lock.

  1. Waiting (WAITING) state: The thread will enter the waiting state under the following circumstances: the wait() method is called, the join() method is called, or the park() method of LockSupport is called. In the wait state, the thread will not actively execute any code until other threads wake it up or the waiting time expires. The following is a sample code using the wait() method:
public class MyThread extends Thread {
    public void run() {
        synchronized(this) {
            System.out.println("Waiting for next thread...");
            try {
                wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println("Thread resumed.");
        }
    }
  
    public static void main(String[] args) {
        MyThread thread = new MyThread();
        thread.start();
  
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        synchronized(thread) {
            thread.notify();
        }
    }
}

In the above code, after the thread enters the waiting state, the main thread wakes up the thread through the notify() method.

  1. Timed waiting (TIMED_WAITING) state: The thread will enter the timed waiting state under the following circumstances: the sleep() method is called, the join() method with a timeout parameter is called, the thread with a timeout parameter is called The wait() method of the timeout parameter, the parkNanos() method or the parkUntil() method of LockSupport is called. In the scheduled waiting state, the thread will not actively execute any code and will be awakened after the waiting time is reached. The following is a sample code using the sleep() method:
public class MyThread extends Thread {
    public void run() {
        try {
            System.out.println("Thread sleeping...");
            Thread.sleep(2000);
            System.out.println("Thread woke up.");
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
  
    public static void main(String[] args) {
        MyThread thread = new MyThread();
        thread.start();
    }
}

In the above code, the thread enters the scheduled waiting state by calling the sleep() method, and waits for 2 seconds before being awakened.

  1. Terminated (TERMINATED) state: After the thread finishes executing the code in the run() method, the thread will enter the terminated state. In the terminated state, the thread will no longer run.

In summary, the status of the thread has an important impact on the execution of the program. Understanding the various states and their meaning is crucial to writing efficient multi-threaded programs.

Reference materials:

  • Oracle official documentation - Java thread status: https://docs.oracle.com/javase/8/docs/api/java/lang/Thread. State.html
  • Java multi-threading introductory tutorial: https://www.journaldev.com/1162/java-thread-tutorial

The above is the detailed content of In-depth study of several states of Java threads and their impact on program execution. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn