In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-01-18 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/02 Report--
This article focuses on "how to understand the java thread life cycle", interested friends may wish to take a look. The method introduced in this paper is simple, fast and practical. Let's let the editor take you to learn how to understand the java thread life cycle.
Several states of thread life cycle
When I first came into contact with the thread life cycle, I couldn't remember or understand their state, which was confusing, not to mention how state transitions were made between them. The reason is that I confuse the general thread state of the operating system with the concept of thread state encapsulated by the programming language.
Operating system universal thread state
Personally, I think the general thread state is more in line with our thinking habits. There are always five states (as shown in the following figure). For students who often write concurrent programs, they often read these general thread states in the operating system. Let's see.
Apart from the birth [initial state] death [termination state], it is actually only the various transitions of the three states. Is it a lot of relief to hear this sentence?
In order to better illustrate the general thread state and the thread state in the Java language, here is a brief description of the former.
Initial state
The thread has been created, but is not allowed to allocate CPU execution. Note that this is actually created at the programming language level. In fact, in the operating system, the real thread has not been created, such as new Thread () in the Java language.
Runnable state
The thread can assign CPU execution. At this time, the thread in the operating system has been created successfully.
Running state
The operating system allocates CPU time slices to threads in a runnable state. After being lucky by CPU, threads in a runnable state will become runnable.
Dormant state
If a running thread calls a blocked API or waits for an event condition to become available, the thread will switch to the dormant state. Note: the thread will release the right to use CPU, and the dormant thread will never get the right to use CPU. Only when the waiting event occurs, the thread will transition from the dormant state to the runnable state.
Termination state
When a thread finishes execution or an exception occurs (which is not counted by interrupt, it will be said later), it will enter the termination state and officially come to the end of life, with no chance to bring the dead back to life.
Next, let's take a look at the Java thread life cycle that you are familiar with, unfamiliar, and often asked about in interviews.
Java language thread state
In the source code of Thread, an enumeration class State is defined, which clearly writes six states of threads in the Java language:
NEW
RUNNABLE
BLOCKED
WAITING
TIMED_WAITING
TERMINATED
The song of the five rings sounded in my ear, and the thread state in Java was one more than the five general thread states, and became six. This may seem complicated, but it's not what you think. Java is tailored and rich on the basis of general thread state, but there is one less on the whole. Let's take another look at the picture and pay attention to the color distinction.
In Java language
Merge the runnable state and running state of the common thread state into a Runnable
Subdivide the dormant state into three types (BLOCKED/WAITING/TIMED_WAITING); in turn, understand this sentence, that is, all three states are dormant in the eyes of the operating system, and they will not get the right to use CPU.
Look at the right side of the figure [thread state in Java language]. To put it more succinctly, apart from thread life and death, we only need to play with the transition between RUNNABLE and hibernation, and writing concurrent programs is mostly the transition of these two states. So we need to know when these state transitions are triggered.
Look at the outline from a distance and take a closer look at the details.
RUNNABLE and BLOCKED state transition
If and only (just only) there is one situation that will go from RUNNABLE state to BLOCKED state, that is, the thread is waiting for the synchronized built-in implicit lock; if the waiting thread acquires the synchronized built-in implicit lock, it will change from BLOCKED state to RUNNABLE state.
Note:
As mentioned above, in terms of the general state of the operating system, when a thread calls blocking API, it will become dormant (releasing the right to use CPU), but at the JVM level, the state of the Java thread will not change, that is, the state of the Java thread will remain in the RUNNABLE state. JVM does not care about the status of operating system scheduling. In JVM's view, waiting for the right to use CPU (the operating system is in an executable state) and waiting for Imax O (the operating system is in a dormant state) are both waiting for a resource, so they all fall into the RUNNABLE state.
-- extracted from "Java concurrent programming practice"
RUNNABLE and WAITING state transition
If you call wait API without a time parameter, you will go from RUNNABLE state to WAITING state; when awakened, you will enter RUNNABLE state from WAITING.
RUNNABLE and TIMED-WAITING state transition
When you call the wait API with a time parameter, you will naturally enter the TIMED-WAITING state from the RUNNABLE state; when you are awakened or the timeout time has expired, you will enter the RUNNABLE state from TIMED_WAITING.
There are a lot of API transitions in the figure. In fact, don't worry. If you analyze the source code chapters later, you will naturally remember them. It would be nice to have an impression and know the node of the state transition.
I believe that at this point, the way you look at the life cycle of Java threads is not so confusing. The key point is the switch between RUNNABLE and hibernation. Next, let's take a look at how to view the state in the thread, as well as the specific code trigger points.
How to see what state the thread is in
Call the getState () method in the program
There is also a getState () method in the Thread class to view the current thread status, which returns the enumerated class State mentioned above.
NEW
As mentioned above, unique to the programming language, when a thread is defined by inheriting Thread or implementing the Runnable interface, the state is NEW.
Thread thread = new Thread (()-> {}); System.out.println (thread.getState ())
RUNNABLE
After calling the start () method, the thread is in the RUNNABLE state
Thread thread = new Thread (()-> {}); thread.start (); / / Thread.sleep (1000); System.out.println (thread.getState ())
BLOCKED
Wait for the synchronized built-in lock, and you will be in the BLOCKED state.
Public class ThreadStateTest {public static void main (String [] args) throws InterruptedException {Thread T1 = new Thread (new DemoThreadB ()); Thread T2 = new Thread (new DemoThreadB ()); t1.start (); t2.start (); Thread.sleep (1000); System.out.println ((t2.getState (); System.exit (0) }} class DemoThreadB implements Runnable {@ Override public void run () {commonResource ();} public static synchronized void commonResource () {while (true) {}
WAITING
Call the thread's join () and other methods to change from RUNNABLE to WAITING state
Public static void main (String [] args) throws InterruptedException {Thread main = Thread.currentThread (); Thread thread2 = new Thread (()-> {try {Thread.sleep (1000);} catch (InterruptedException e) {Thread.currentThread () .interrupt (); e.printStackTrace () } System.out.println (main.getState ());}); thread2.start (); thread2.join ();}
TIMED-WAITING
Methods such as sleep (long) are called, and the thread changes from RUNNABLE to TIMED-WAITING state.
Public static void main (String [] args) throws InterruptedException {Thread thread3 = new Thread (() -) > {try {Thread.sleep (3000);} catch (InterruptedException e) {/ / Why should I call the interrupt method? Thread.currentThread () .interrupt (); e.printStackTrace ();}}); thread3.start (); Thread.sleep (1000); System.out.println (thread3.getState ());}
TERMINATED
When the thread finishes executing, it naturally reaches the TERMINATED state.
Thread thread = new Thread (()-> {}); thread.start (); Thread.sleep (1000); System.out.println (thread.getState ())
The above is to view the thread in the program, write your own test to see if the status is fine, how can the real program allow you to add so much useless code, so, Cuihua, serve sauerkraut (jstack)
Jstack command view
I believe you have heard of this thing, the jstack command is more powerful, not only to see the current state of the thread, but also to see the call stack, locks and other thread stack information
You can write some programs at will. Here I use the code of the above WAITING status to modify the sleep time Thread.sleep (100000), and then execute the following command at the terminal according to the following figure.
For more functions, please check for yourselves. Later, we will write separate articles to teach you how to use jstack to view thread stack information.
Arthas
There is no need to say much about this sharp weapon. There is nothing wrong with online fault monitoring. I hope you can use this tool flexibly to overcome difficult and complicated diseases.
At this point, I believe you have a deeper understanding of "how to understand the java thread life cycle". You might as well do it in practice. Here is the website, more related content can enter the relevant channels to inquire, follow us, continue to learn!
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.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.