Home > Java > javaTutorial > body text

A detailed description of the five states of Java threads and their characteristics and performance in multi-threaded environments

WBOY
Release: 2024-02-18 19:07:05
Original
568 people have browsed it

A detailed description of the five states of Java threads and their characteristics and performance in multi-threaded environments

Details the five states of Java threads and their characteristics and performance in a multi-threaded environment

Java is an object-oriented programming language, and its multi-threading The features allow us to perform multiple tasks at the same time, improving the concurrency and responsiveness of the program. In Java, threads have five different states, namely new state (New), runnable state (Runnable), blocked state (Blocked), waiting state (Waiting) and terminated state (Terminated). This article will introduce the characteristics of these five states in detail, and show the performance in a multi-threaded environment through specific code examples.

1. New state (New)
The state in which a thread is created but has not yet started running is called the new state. In the newly created state, the thread's start() method has not yet been called, so execution has not actually started yet. At this point, the thread object has been created, but the operating system has not allocated execution resources to it.

2. Runnable state (Runnable)
After the thread is called by the start() method, it enters the runnable state. The thread in this state is using the CPU to perform its tasks, but may be suspended due to other high-priority threads, running out of time slices, or waiting for input/output. In the runnable state, threads have the following characteristics:

  1. The thread in this state is the basic unit of operating system scheduling.
  2. Multiple threads execute concurrently, and CPU time slices are allocated to each thread so that they execute alternately.
  3. Thread scheduling is uncontrollable because it is determined by the operating system.

The following is a simple code example showing the runnable status of two threads:

class MyRunnable implements Runnable{
    public void run(){
        for(int i=0; i<10; i++){
            System.out.println(Thread.currentThread().getName() + ": " + i);
        }
    }
}

public class Main {
    public static void main(String[] args) {
        Thread t1 = new Thread(new MyRunnable());
        Thread t2 = new Thread(new MyRunnable());
        
        t1.start();
        t2.start();
    }
}
Copy after login

In the above example, we created two threads t1 and t2, and start them simultaneously. Since both threads run concurrently, their output will alternate.

3. Blocked state (Blocked)
The thread enters the blocking state because it cannot obtain certain resources or waits for certain conditions to be met. A thread in a blocked state will not consume CPU time until it obtains resources or enters a runnable state when conditions are met.

The following is a simple code example showing the blocking state of a thread:

public class Main {
    public static void main(String[] args) {
        Object lock = new Object();
        
        Thread t1 = new Thread(() -> {
            synchronized (lock) {
                try {
                    System.out.println("Thread 1 is waiting");
                    lock.wait();
                    System.out.println("Thread 1 is running again");
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        });

        Thread t2 = new Thread(() -> {
            try {
                Thread.sleep(2000);
                
                synchronized (lock) {
                    System.out.println("Thread 2 is waking up Thread 1");
                    lock.notify();
                }
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        });
        
        t1.start();
        t2.start();
    }
}
Copy after login

In the above example, we created two threads t1 and t2, t1 is in the execution process Enter the waiting state by calling the wait() method until t2 wakes it up through the notify() method. The reason t1 is blocked here is that it cannot continue execution until t2 issues notification. When t2 sends a notification, t1 unblocks and re-enters the runnable state.

4. Waiting state (Waiting)
The thread enters the waiting state because it needs to wait for other threads to take some specific actions. A thread in a waiting state waits until it is notified or interrupted.

The following is a simple code example showing the waiting state of a thread:

public class Main {
    public static void main(String[] args) {
        Object lock = new Object();
        
        Thread t1 = new Thread(() -> {
            synchronized (lock) {
                System.out.println("Thread 1 is waiting");
                try {
                    lock.wait(); // 进入等待状态
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                
                System.out.println("Thread 1 is running again");
            }
        });

        Thread t2 = new Thread(() -> {
            try {
                Thread.sleep(2000);
                
                synchronized (lock) {
                    System.out.println("Thread 2 is waking up Thread 1");
                    lock.notify(); // 唤醒等待的线程
                }
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        });
        
        t1.start();
        t2.start();
    }
}
Copy after login

In the above example, we make the t1 thread enter the waiting state through the lock.wait() method, Until the t2 thread notifies it through the lock.notify() method.

5. Terminated state (Terminated)
When a thread completes its task or exits due to an exception, it enters the terminated state. A thread in the terminated state is no longer executing and cannot be started again.

The following is a simple code example showing the termination status of a thread:

public class Main {
    public static void main(String[] args) {
        Thread t1 = new Thread(() -> {
            for(int i=0; i<10; i++){
                System.out.println(Thread.currentThread().getName() + ": " + i);
            }
        });
        
        t1.start();
        
        try {
            t1.join(); // 确保线程执行完
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        
        System.out.println("Thread 1 is terminated");
    }
}
Copy after login

In the above example, we created a thread t1 and started it. Then use the t1.join() method to ensure that the thread continues to execute subsequent code after it has finished executing.

To sum up, this article introduces the five states of Java threads and their characteristics and performance in a multi-threaded environment. For multi-threaded programming, it is crucial to understand the transitions and characteristics of thread states. Using appropriate thread states can make the program more efficient and reliable. I hope that through the introduction of this article, readers can better understand the working mechanism of Java threads and correctly use multi-threaded programming in actual projects.

The above is the detailed content of A detailed description of the five states of Java threads and their characteristics and performance in multi-threaded environments. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!