search
HomeJavajavaTutorialIn-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

Feb 21, 2024 pm 11:27 PM
stateInfluencejava multithreadingjava thread

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
How does IntelliJ IDEA identify the port number of a Spring Boot project without outputting a log?How does IntelliJ IDEA identify the port number of a Spring Boot project without outputting a log?Apr 19, 2025 pm 11:45 PM

Start Spring using IntelliJIDEAUltimate version...

How to elegantly obtain entity class variable names to build database query conditions?How to elegantly obtain entity class variable names to build database query conditions?Apr 19, 2025 pm 11:42 PM

When using MyBatis-Plus or other ORM frameworks for database operations, it is often necessary to construct query conditions based on the attribute name of the entity class. If you manually every time...

How to use the Redis cache solution to efficiently realize the requirements of product ranking list?How to use the Redis cache solution to efficiently realize the requirements of product ranking list?Apr 19, 2025 pm 11:36 PM

How does the Redis caching solution realize the requirements of product ranking list? During the development process, we often need to deal with the requirements of rankings, such as displaying a...

How to safely convert Java objects to arrays?How to safely convert Java objects to arrays?Apr 19, 2025 pm 11:33 PM

Conversion of Java Objects and Arrays: In-depth discussion of the risks and correct methods of cast type conversion Many Java beginners will encounter the conversion of an object into an array...

How do I convert names to numbers to implement sorting and maintain consistency in groups?How do I convert names to numbers to implement sorting and maintain consistency in groups?Apr 19, 2025 pm 11:30 PM

Solutions to convert names to numbers to implement sorting In many application scenarios, users may need to sort in groups, especially in one...

E-commerce platform SKU and SPU database design: How to take into account both user-defined attributes and attributeless products?E-commerce platform SKU and SPU database design: How to take into account both user-defined attributes and attributeless products?Apr 19, 2025 pm 11:27 PM

Detailed explanation of the design of SKU and SPU tables on e-commerce platforms This article will discuss the database design issues of SKU and SPU in e-commerce platforms, especially how to deal with user-defined sales...

How to set the default run configuration list of SpringBoot projects in Idea for team members to share?How to set the default run configuration list of SpringBoot projects in Idea for team members to share?Apr 19, 2025 pm 11:24 PM

How to set the SpringBoot project default run configuration list in Idea using IntelliJ...

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools