Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

What is the life cycle of threads in Java

2025-03-31 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/02 Report--

This article mainly introduces the relevant knowledge of "what is the life cycle of threads in Java". The editor shows you the operation process through an actual case. The operation method is simple, fast and practical. I hope this article "what is the life cycle of threads in Java" can help you solve the problem.

The life cycle of threads in the operating system

The thread life cycle of the operating system can basically be described by the five-state model shown below. The five states are: initial state, runnable state, running state, dormant state and terminated state.

The details of the five-state model are shown below.

1. Initial state: means that the thread has been created, but the allocation of CPU execution is not allowed. This state is specific to the programming language, but here the so-called created is only created at the programming language level, while at the operating system level, the real thread has not yet been created.

two。 Runnable status: means that threads can assign CPU execution. In this state, the real operating system thread has been successfully created, so CPU execution can be allocated.

3. When there is an idle CPU, the operating system assigns it to a runnable thread, and the state of the thread assigned to the CPU transitions to the running state.

4. If a running thread calls a blocked API (such as reading a file in a blocked way) or waits for an event (such as a condition variable), the thread's state transitions to a dormant state and releases the right to use CPU, and the dormant thread never has a chance to get the right to use CPU. When a waiting event occurs, the thread transitions from dormant to runnable.

5. When a thread finishes execution or an exception occurs, it will enter the termination state, and the thread in the termination state will not switch to any other state, and entering the termination state means that the life cycle of the thread is over.

Runnable state and running state are combined in Java, which are useful at the operating system scheduling level, while the JVM level does not care about these two states, because JVM leaves thread scheduling to the operating system to deal with, and Java refines the sleep state and so on.

Life cycle of threads in Java

Next, let's take a look at the life cycle of threads in Java. There are six states of threads in Java. They are:

1.NEW (initialization status)

2.RUNNABLE (runnable / operational status)

3.BLOCKED (blocking state)

4.WAITING (unlimited waiting)

5.TIMED_WAITING (waiting for a time limit)

6.TERMINATED (termination status)

At the operating system level, BLOCKED (blocking state), WAITING (unlimited waiting) and TIMED_WAITING (limited waiting) in Java threads are a kind of state, namely dormant state. That is, as long as the Java thread is in one of these three states, the thread will never have access to CPU.

So the life cycle of the Java thread can be simplified to the following figure:

Among them, BLOCKED (blocking state), WAITING (unlimited waiting) and TIMED_WAITING (limited waiting) can be understood as the three causes of thread sleep state. So what are the circumstances that cause threads to transition from the RUNNABLE state to these three states? And when did these three states switch back to RUNNABLE? And how do NEW, TERMINATED, and RUNNABLE states transition?

1. State transition between RUNNABLE and BLOCKED

The only scenario that triggers this transformation is that the thread waits for an implicit lock on the synchronized. Synchronized-decorated methods and blocks of code allow only one thread to execute at a time, while other threads can only wait, in which case the waiting thread transitions from RUNNABLE to BLOCKED state. When the waiting thread acquires the synchronized implicit lock, it transitions from BLOCKED to RUNNABLE state.

If you are familiar with the life cycle of operating system threads, you may have a question: when a thread calls a blocking API, will it switch to the BLOCKED state? At the operating system level, threads will transition to sleep, but at the JVM level, the state of Java threads will not change, that is, the state of Java threads will remain in RUNNABLE state. The JVM level does not care about the status related to operating system scheduling, because in JVM's view, there is no difference between waiting for the right to use CPU (the operating system level is executable at this time) and waiting for CPU O (the operating system level is dormant at this time). They are both waiting for a resource, so they are all classified into RUNNABLE status.

The so-called Java will block when calling the blocking API, which refers to the state of the operating system thread, not the state of the Java thread.

2. State transition between RUNNABLE and WAITING

Overall, there are three scenarios that trigger this transformation.

In the first scenario, the thread that acquires the synchronized implicit lock invokes the parameterless Object.wait () method.

In the second scenario, the parameterless Thread.join () method is called. Join () is a thread synchronization method. For example, there is a thread object thread A. When A.join () is called, the thread executing this statement waits for thread A to finish execution, while the waiting thread transitions its state from RUNNABLE to WAITING. When thread thread A finishes executing, the thread that was waiting for it transitions from the WAITING state to RUNNABLE.

In the third scenario, the LockSupport.park () method is called. The LockSupport object among them may be a little strange to you, but in fact, the locks in the Java concurrent package are all based on it. When the LockSupport.park () method is called, the current thread blocks and the thread's state transitions from RUNNABLE to WAITING. Calling LockSupport.unpark (Thread thread) wakes up the target thread, and the state of the target thread transitions from the WAITING state to the RUNNABLE.

3. State transition between RUNNABLE and TIMED_WAITING

There are five scenarios that trigger this transformation:

Call the Thread.sleep (long millis) method with a timeout parameter

The thread that acquires the synchronized implicit lock calls the Object.wait (long timeout) method with a timeout parameter

Call the Thread.join (long millis) method with a timeout parameter

Call the LockSupport.parkNanos (Object blocker, long deadline) method with a timeout parameter

Call the LockSupport.parkUntil (long deadline) method with a timeout parameter.

Here you will find that the difference between TIMED_WAITING and WAITING states is that the trigger condition has more timeout parameters.

4. From NEW to RUNNABLE statu

The Thread object that Java has just created is the NEW state, and there are two main ways to create Thread objects. One is to inherit the Thread object and override the run () method. The sample code is as follows:

Public class MyThread extends Thread {@ Override public void run () {/ / the code that the thread needs to execute System.out.println (Thread.currentThread (). GetName ());} public static void main (String [] args) {/ / create thread object MyThread myThread = new MyThread ();}}

The other is to implement the Runnable interface, override the run () method, and take the implementation class as a parameter to create a Thread object. The sample code is as follows:

Public class Runner implements Runnable {@ Override public void run () {/ / the code that the thread needs to execute System.out.println (Thread.currentThread (). GetName ());} public static void main (String [] args) {/ / create thread object Thread thread = new Thread (new Runner ());}}

Threads in NEW state are not scheduled by the operating system and therefore will not be executed. For the Java thread to execute, it must transition to the RUNNABLE state. The transition from NEW state to RUNNABLE state is simple, as long as you call the thread object's start () method. The sample code is as follows:

Public class Runner implements Runnable {@ Override public void run () {/ / the code that the thread needs to execute System.out.println (Thread.currentThread (). GetName ());} public static void main (String [] args) {/ / create thread object Thread thread = new Thread (new Runner ()) / / transition from NEW state to RUNNABLE state thread.start ();}}

5. From RUNNABLE to TERMINATED statu

After the thread finishes executing the run () method, it automatically transitions to the TERMINATED state, although if an exception is thrown when the run () method is executed, it will also cause the thread to terminate. Sometimes we need to forcibly interrupt the execution of the run () method. For example, the run () method accesses a slow network. We can't wait any longer. What if we want to stop? there is a stop () method in Java's Thread class, but it is already marked @ Deprecated, so it is not recommended. The correct pose is actually a call to the interrupt () method.

Java.lang.Thread#stop () source code:

@ Deprecated public final void stop () {SecurityManager security = System.getSecurityManager (); if (security! = null) {checkAccess (); if (this! = Thread.currentThread ()) {security.checkPermission (SecurityConstants.STOP_THREAD_PERMISSION);}} if (threadStatus! = 0) {resume ();} stop0 (new ThreadDeath ());}

So what is the main difference between the stop () and interrupt () methods?

The stop () method really kills the thread, and if the thread holds the ReentrantLock lock, the thread being stop () will not automatically call ReentrantLock's unlock () to release the lock, then other threads will never get a chance to acquire the ReentrantLock lock, which is too dangerous. So this method is not recommended, and similar methods include the suspend () and resume () methods, neither of which is recommended.

The interrupt () method simply notifies the thread, which has the opportunity to perform some subsequent actions and can ignore the notification. How does the thread being interrupt receive the notification? One is abnormal, the other is active detection.

When thread An is in WAITING, TIMED_WAITING state, if other threads call thread A's interrupt () method, thread A will return to the RUNNABLE state, and thread A's code will trigger an InterruptedException exception. The trigger conditions mentioned above for transitioning to WAITING and TIMED_WAITING state are all called methods such as wait (), join () and sleep (). When we look at the signatures of these methods, we find that they all throws InterruptedException this exception. The exception is triggered by another thread calling the thread's interrupt () method.

When thread An is in RUNNABLE state and is blocked on java.nio.channels.InterruptibleChannel, thread A will trigger the exception java.nio.channels.ClosedByInterruptException if other threads call thread A's interrupt () method, while when thread An is blocked on java.nio.channels.Selector, thread A's java.nio.channels.Selector will return immediately if other threads call thread A's interrupt () method.

In both cases, the interrupted thread is notified by an exception. The other is active detection. If the thread is in RUNNABLE state and does not block on some Imax O operation, such as interrupt thread A, it has to rely on thread A to actively detect the interrupt state. If other threads call thread A's interrupt () method, thread A can use the isInterrupted () method to detect whether it has been interrupted.

This is the end of the content about "what is the life cycle of threads in Java". Thank you for reading. If you want to know more about the industry, you can follow the industry information channel. The editor will update different knowledge points for you every day.

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report