search
HomeJavajavaTutorialIntroduction to the life cycle of Java threads (with examples)

This article brings you an introduction to the life cycle of Java threads (with examples). It has certain reference value. Friends in need can refer to it. I hope it will be helpful to you.

1. Thread life cycle

Processes, like threads, have a certain life cycle. The thread life cycle includes four states: creation state, ready state, blocking state, and death state. .

1. Creation state

1) refers to using new to instantiate a thread object, but the thread object has not yet used the start() method to start the thread. This stage is only in the memory. The memory space is allocated for the instance variable of the object in the heap, but the thread cannot participate in grabbing the right to use the CPU;

2) After the thread object is created, the start() method is used to start the thread object, and Not the run() method.

2. Ready state

1) refers to the stage from when a thread object uses the start() method to finishing running the run() method. Once the thread enters the ready stage, the Java virtual machine Create the call stack and counter of the method for the thread;

2) Within a certain unit time (time slice), the CPU can only run one thread. Once a thread has the right to use the CPU, then This thread can also be called the running state;

3) All threads in the ready state are considered active. You can use the isAlive() method to test whether the thread is in the ready state, and use activeCount() to query the current The number of active threads in the thread pool where the thread is located;

4) The thread in the ready state is not in the running state. In the past, many computers were single-processor, and all threads in the ready state must be run at the same time. It is impossible. Java uses some scheduling algorithms to ensure that these threads share the use of the processor (such as time slice rotation algorithm, exclusive algorithm, etc.).

3. Blocking state:

1) The blocking state includes four states (sleep state, blocking state, suspend state, waiting state). Generally speaking, the blocking state and The ready state can be switched between each other;

2) Use the sleep() method to put the thread into sleep state, allowing other processes to get a chance to run, but using the sleep method must capture the InterruptedExecption exception;

3) You can use the suspend method to suspend a thread (obsolete after jdk1.2), use the wait method to put a thread into a waiting state (there will be an essay dedicated to it later), and use I/O interrupts to put a thread into a blocking state.

4. Death state:

1) Once the thread finishes running the run method, the thread enters the death state, and the Java virtual machine destroys the system resources occupied by the thread object in the death state;

2) When the thread encounters an uncaught exception during execution, the thread will be terminated and enter the death state; calling the stop method can also cause the thread to enter the death state, but it is easy to cause deadlock and has been deprecated.

5. The thread life cycle is as follows:

2. The following is a case where the sleep method puts the thread into sleep state

/**
 * @author: PrincessHug
 * @date: 2019/4/12, 9:20
 * @Blog: https://www.cnblogs.com/HelloBigTable/
 */
public class SleepDemo  implements Runnable{
    @Override
    public void run() {
        long l;
        for (int i=1;i<6;i++){
            l = System.currentTimeMillis();
            try {
                Thread.currentThread().sleep(5000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            l = (System.currentTimeMillis() - l);
            System.out.println(Thread.currentThread().getName() + "线程执行了" + i + "次,耗时" + l + "毫秒。");
        }
    }
}
public class SleepDriver {
    public static void main(String[] args) {
        SleepDemo sd = new SleepDemo();
        for (int i=0;i<50;i++){
            new Thread(sd,i + "#").start();
        }
    }
}

The following are some screenshots of the running results:

You can see if at the same time The more threads started, the longer each thread will take.

The above is the detailed content of Introduction to the life cycle of Java threads (with examples). For more information, please follow other related articles on the PHP Chinese website!

Statement
This article is reproduced at:segmentfault. If there is any infringement, please contact admin@php.cn delete
How does the JVM contribute to Java's 'write once, run anywhere' (WORA) capability?How does the JVM contribute to Java's 'write once, run anywhere' (WORA) capability?May 02, 2025 am 12:25 AM

JVM implements the WORA features of Java through bytecode interpretation, platform-independent APIs and dynamic class loading: 1. Bytecode is interpreted as machine code to ensure cross-platform operation; 2. Standard API abstract operating system differences; 3. Classes are loaded dynamically at runtime to ensure consistency.

How do newer versions of Java address platform-specific issues?How do newer versions of Java address platform-specific issues?May 02, 2025 am 12:18 AM

The latest version of Java effectively solves platform-specific problems through JVM optimization, standard library improvements and third-party library support. 1) JVM optimization, such as Java11's ZGC improves garbage collection performance. 2) Standard library improvements, such as Java9's module system reducing platform-related problems. 3) Third-party libraries provide platform-optimized versions, such as OpenCV.

Explain the process of bytecode verification performed by the JVM.Explain the process of bytecode verification performed by the JVM.May 02, 2025 am 12:18 AM

The JVM's bytecode verification process includes four key steps: 1) Check whether the class file format complies with the specifications, 2) Verify the validity and correctness of the bytecode instructions, 3) Perform data flow analysis to ensure type safety, and 4) Balancing the thoroughness and performance of verification. Through these steps, the JVM ensures that only secure, correct bytecode is executed, thereby protecting the integrity and security of the program.

How does platform independence simplify deployment of Java applications?How does platform independence simplify deployment of Java applications?May 02, 2025 am 12:15 AM

Java'splatformindependenceallowsapplicationstorunonanyoperatingsystemwithaJVM.1)Singlecodebase:writeandcompileonceforallplatforms.2)Easyupdates:updatebytecodeforsimultaneousdeployment.3)Testingefficiency:testononeplatformforuniversalbehavior.4)Scalab

How has Java's platform independence evolved over time?How has Java's platform independence evolved over time?May 02, 2025 am 12:12 AM

Java's platform independence is continuously enhanced through technologies such as JVM, JIT compilation, standardization, generics, lambda expressions and ProjectPanama. Since the 1990s, Java has evolved from basic JVM to high-performance modern JVM, ensuring consistency and efficiency of code across different platforms.

What are some strategies for mitigating platform-specific issues in Java applications?What are some strategies for mitigating platform-specific issues in Java applications?May 01, 2025 am 12:20 AM

How does Java alleviate platform-specific problems? Java implements platform-independent through JVM and standard libraries. 1) Use bytecode and JVM to abstract the operating system differences; 2) The standard library provides cross-platform APIs, such as Paths class processing file paths, and Charset class processing character encoding; 3) Use configuration files and multi-platform testing in actual projects for optimization and debugging.

What is the relationship between Java's platform independence and microservices architecture?What is the relationship between Java's platform independence and microservices architecture?May 01, 2025 am 12:16 AM

Java'splatformindependenceenhancesmicroservicesarchitecturebyofferingdeploymentflexibility,consistency,scalability,andportability.1)DeploymentflexibilityallowsmicroservicestorunonanyplatformwithaJVM.2)Consistencyacrossservicessimplifiesdevelopmentand

How does GraalVM relate to Java's platform independence goals?How does GraalVM relate to Java's platform independence goals?May 01, 2025 am 12:14 AM

GraalVM enhances Java's platform independence in three ways: 1. Cross-language interoperability, allowing Java to seamlessly interoperate with other languages; 2. Independent runtime environment, compile Java programs into local executable files through GraalVMNativeImage; 3. Performance optimization, Graal compiler generates efficient machine code to improve the performance and consistency of Java programs.

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.

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.