Detailed explanation of the life cycle of Java threads
Detailed explanation of the life cycle of Java threads
For multithreaded programming, understanding the life cycle of threads is very important. This article explains this point.
1、 Status of the thread
Threads exist in several different states, as follows:
1. New status
The new state is a state in which the thread has been created but has not yet started running. This state allows the thread to run by calling the thread's start () method.
2. Runnable status
The runnable state can be called ready to run or queue. This state allows the thread to run by calling the thread's start () method. The thread scheduler determines which threads to run and how long.
3. Running status
If a thread is executing, it is in the running state.
4. Dead status
Once a thread enters the dead state, it can no longer run.
5. Non runnable status
A running thread can transition to the non runnable state, depending on the operation. A thread can also remain in the non runnable state until the conditions are met. A thread in a non runnable state cannot jump directly to the running state, but must first change to the runnable state. Sleep sleeping: the specified time the thread sleeps. I / O blocking: the thread waits until the blocking operation is completed. Join blocking: a thread waits until another thread completes execution. Wait for notification: a thread waits for notification from another thread. Lock mechanism blocking: the thread waits until the specified lock is released to obtain the lock.
The Java virtual machine JVM executes threads according to thread priority and scheduling principles.
2、 Thread scheduler
In the JVM, the implementation of thread scheduler is usually based on the following two strategies:
The implementation of thread scheduler is platform independent, so thread scheduling is unpredictable.
3、 Thread priority
The JVM assigns a priority to each newly created thread.
To save these values, the thread class has three corresponding variables:
A thread will first inherit the priority of its parent thread. The default priority of each thread is level 5 (normal priority), and the default priority of the main thread is level 5.
You can set the priority of a thread through the setpriority (int priority) method.
For user-defined threads, the default thread name is thread + sequence number, which starts from 0. For example, the first thread is thread0. The thread name can be set through the setname (string name) method, and the thread name can be obtained using the getname () method.
example
Here is an example:
Output results:
If you have any questions, please leave a message or go to the community of this site for exchange and discussion. Thank you for reading. I hope it can help you. Thank you for your support to this site!