In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-01-19 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Servers >
Share
Shulou(Shulou.com)06/01 Report--
How to achieve thread state switching in Java, in view of this problem, this article introduces the corresponding analysis and solution in detail, hoping to help more partners who want to solve this problem to find a more simple and easy way.
What is the Java thread state
In a Java program, used to describe the six states of a Java thread:
New (NEW): the current thread, which has just been created, has not been started.
RUNNABLE: the current thread is in a state where CPU time slicing is competing or CPU time slices have been obtained.
WAITTING: the current thread, which is dormant, does not compete for CPU time slices.
Timed wait (TIMED_WAITTING): the current thread, which is scheduled to sleep, is temporarily not competing for CPU time slices.
BLOCKED: the current thread, which is blocked, does not compete for CPU time slices.
TERMINATED: the current thread, in the final stopped state.
New state, can only enter the running state. The terminated state cannot be changed to another state.
The difference between waiting / scheduled waiting and blocking is that the latter requires an event signal (such as other threads to give up the exclusive lock needed by the current thread) before state switching can take place. Of course, it is also possible to close it by force.
The implementation of Java threads is not constrained by the JVM specification, so the implementation of different virtual machines is often different. At present, the mainstream HotSpot is to map each Java thread directly to a native thread of an operating system, so that the operating system completes a series of thread scheduling.
Second, where to see the Java thread status
There are three main ways to view Java thread status:
Six thread states of Java can be seen directly under java.lang.Thread.State.
When Java is running, the target thread status can be obtained inside the program through Thread.getState ().
When Java is running, the thread status can be viewed outside the program through tools such as jstack.
With regard to the use of tools such as jstack, there will be a blog dedicated to it.
When to change the state of Java threads
Switching the state of Java threads. Don't be wordy, just go straight to the picture.
This diagram covers various methods of Java thread state switching. Compared with some pictures on the Internet, it is more detailed.
If there is any omission, please let me know and I will fill it in time.
Who is using Java thread state
In day-to-day development, we do not interact directly with thread state.
We often use tools packaged by JDK directly, such as all kinds of tools under JUC package.
Take a chestnut.
Application in thread pool
Location: com.sun.corba.se.impl.orbutil.threadpool.ThreadPoolImpl#close
/ / Note that this method should not return until AFTER all threads have died.
Public void close () throws IOException {
/ / Copy to avoid concurrent modification problems.
List copy = null
Synchronized (workersLock) {
Copy = new ArrayList (workers)
}
For (WorkerThread wt: copy) {
Wt.close ()
While (wt.getState ()! = Thread.State.TERMINATED) {
Try {
Wt.join ()
} catch (InterruptedException exc) {
Wrapper.interruptedJoinCallWhileClosingThreadPool (exc, wt, this)
}
}
}
ThreadGroup = null
}
After actually looking at the JDK, it is found that there are not so many hot instances in JDK, and most of the things that are directly related to thread state are also something to look at.
At the beginning of the article, it is said that Java thread operation is very low-level, and even its implementation is not included in the virtual machine specification.
The mainstream HotSpot also directly maps Java threads to system threads, and the system carries out a series of thread scheduling processing.
Therefore, in JDK, there are very few parts that deal with thread state directly.
Fifth, why do you need thread state 1. Why the concept of thread state is needed
This problem can be explained from two angles: life cycle and resource management.
On the one hand, the thread state well depicts the whole life cycle of the thread, and effectively divides the different stages of the life cycle.
On the other hand, resources are limited and demand is unlimited. Therefore, it is necessary to schedule the system resources consciously, make rational use of comparative advantages, and pursue Pareto optimality.
The latter is realized by using the state description and grouping brought by the natural attribute of threads at different stages of the life cycle. CPU scheduling only needs to focus on the running state of the thread. And blocking, waiting and other threads have their own set of processing methods. Finally, the optimal allocation of resources (the response to complexity during development, the consumption of system resources at runtime, the growth of the mental model of the user, etc.) is obtained.
Why Java thread state needs to be defined in 2.JDK
As mentioned earlier, thread state is rarely used directly in Java. So why define the six thread states of Java in JDK?
On the one hand, through the way of information transparency, it can reduce the cost of building mental models for users. For example, now we can print logs, break points, quickly understand the status of each thread of Java, and clearly understand the cause. This greatly improves our understanding of Java threads and makes it more enjoyable to embrace tools such as thread pools under the JUC package.
On the other hand, through the state enumeration that can be applied directly, we can make a good secondary development of the existing tools. For example, we can get a customized thread synchronization tool by extending AQS and adding thread state check to it.
6. How to use thread state
Use the way, I have already mentioned above: learn Java threads, customize thread-related tool development.
Here is a demo about thread learning:
/ * *
* @ program: learning
* @ description: used to confirm thread status problems
* @ author: Jarry
* @ create: 2020-10-26 22:25
* * /
Public class ThreadState {
Public static void main (String [] args) {
ThreadStateTest ()
/ / threadStateTest2 ()
/ / threadStateWithBlocked ()
/ / threadStateWithException ()
/ / threadStateWithSuspend ()
}
/ * *
* practice has proved that Thread.suspend () and Thread.resume () do not change the thread state.
* Thread state should be Waiting, just Waiting. The Timed_Waiting is Timed_Waiting.
* Thread.suspend () and Thread.resume () just suspend the target thread (and do not release lock resources)
, /
Private static void threadStateWithSuspend () {
Thread thread1 = new Thread (()-> {
/ / LockSupport.park ()
LockSupport.parkNanos (2000000000)
});
Thread1.start ()
PrintThreadState (thread1)
LockSupport.parkNanos (500000000)
PrintThreadState (thread1)
Thread1.suspend ()
PrintThreadState (thread1)
LockSupport.parkNanos (500000000)
PrintThreadState (thread1)
Thread1.resume ()
LockSupport.parkNanos (500000000)
PrintThreadState (thread1)
/ / LockSupport.unpark (thread1)
}
/ * *
* show thread blocking status
, /
Private static void threadStateWithBlocked () {
Runnable runnable = new Runnable () {
@ Override
Public void run () {
Synchronized (ThreadState.class) {
/ / LockSupport.parkNanos (2000000000)
LockSupport.park ()
}
}
}
Thread thread1 = new Thread (runnable)
Thread thread2 = new Thread (runnable)
Thread1.start ()
LockSupport.parkNanos (500000000)
Thread2.start ()
/ / add the following time interval, the result: Runnable- > Blocked
/ corollary: Thread.start () will set the thread state to Runnable, and then switch to Blocked state when it encounters a sync lock
/ / LockSupport.parkNanos (500000000)
PrintThreadState (thread2)
LockSupport.parkNanos (500000000)
PrintThreadState (thread2)
LockSupport.parkNanos (500000000)
LockSupport.unpark (thread1)
LockSupport.unpark (thread2)
}
/ * *
* due to the difference of the underlying implementation mechanism (compared with other waiting methods), Object.wait () cannot be done directly, otherwise the following exception will be thrown
* @ exception java.lang.IllegalMonitorStateException
* the method for object.wait () to wait is to operate on its wait_set directly
, /
Private static void threadStateWithException () {
Thread thread1 = new Thread (()-> {
Try {
ThreadState.class.wait (2000)
} catch (InterruptedException e) {
E.printStackTrace ()
}
});
Thread1.start ()
LockSupport.parkNanos (1000000000)
PrintThreadState (thread1)
}
/ * *
* use of Object.wait ()
, /
Private static void threadStateTest3 () {
Thread thread1 = new Thread (()-> {
Synchronized (ThreadState.class) {
Try {
ThreadState.class.wait (2000)
} catch (InterruptedException e) {
E.printStackTrace ()
}
}
});
Thread1.start ()
LockSupport.parkNanos (1000000000)
PrintThreadState (thread1)
}
/ * *
* determine whether LockSupport.parkNacos () can generate Time_Waiting status
, /
Private static void threadStateTest2 () {
Thread thread1 = new Thread (()-> {
LockSupport.parkNanos (2000000000)
});
Thread1.start ()
PrintThreadState (thread1)
LockSupport.parkNanos (1000000000)
PrintThreadState (thread1)
}
/ * *
* View all thread states except Blocked
, /
Private static void threadStateTest () {
Thread thread1 = new Thread (()-> {
Synchronized (ThreadState.class) {
/ / Runnable
PrintThreadState (Thread.currentThread ())
/ / 1.Thread.sleep (time)
Try {
Thread.sleep (2000)
} catch (InterruptedException e) {
E.printStackTrace ()
}
/ / 2.Object.wait (time)
/ / try {
/ / ThreadState.class.wait (2000)
/ /} catch (InterruptedException e) {
/ / e.printStackTrace ()
/ /}
/ / 3.Thread.join (time)
/ / try {
/ Thread.currentThread () .join (2000)
/ /} catch (InterruptedException e) {
/ / e.printStackTrace ()
/ /}
/ / 4.LockSupport.parkNanos (time)
/ / LockSupport.parkNanos (2000000000)
/ / 5.LockSupport.parkUntil (timeStamp)
/ / LockSupport.parkUntil (System.currentTimeMillis () + 2000)
LockSupport.park ()
}
});
Thread1.setName ("test_thread")
/ / New
PrintThreadState (thread1)
Thread1.start ()
LockSupport.parkNanos (1000000000)
/ / Timed_waiting
PrintThreadState (thread1)
LockSupport.parkNanos (2000000000)
/ / Waiting
PrintThreadState (thread1)
LockSupport.unpark (thread1)
LockSupport.parkNanos (1000000000)
/ / Terminated
PrintThreadState (thread1)
}
Private static void printThreadState (Thread thread) {
System.out.println ("current Thread (" + thread.getName () + ":" + thread.getId () + ") state:" + thread.getState ())
}
}
There are some detailed knowledge points in the code, so I won't repeat them here. If you are interested, you can take a look at the notes and verify by yourself.
VII. Extension: system state (three states & five states)
The operating system includes process management, job management, file management and so on. Among them, process management involves three-state model and five-state model of system state.
Among them, the three-state model contains the following three states:
Ready state
Running state
Blocking state
The five-state model contains the following five states:
Running state
Static ready state
Active and ready
Static blocking state
Active blocking state
For specific status switching, you can take a look at a blog I wrote earlier:
System architect-operating system
Finally, I would like to make progress with you.
Appendix add: the difference between WAITTING/TIMED_WAITTING and BLOCKED
Actually, I was struggling with this problem before.
The idea at the time was that WAITTING/TIMED_WAITTING was maintained by JVM itself and BLOCKED was maintained by the system. As you'll see later, the mainstream HotSpot maps threads to system native threads, so this idea is probably wrong.
So what's the difference between the two?
Until in my sample code above, a thread in BLOCKED state changes to a RUNNING state and then to another state when other threads release the locks they need. It got my attention.
Finally, in an article by stackOverFlow (Difference between WAIT and BLOCKED thread states), I saw this explanation:
The important difference between the blocked and wait states is the impact on the scheduler. A thread in a blocked state is contending for a lock; that thread still counts as something the scheduler needs to service, possibly getting factored into the scheduler's decisions about how much time to give running threads (so that it can give the threads blocking on the lock a chance).
Once a thread is in the wait state the stress it puts on the system is minimized, and the scheduler doesn't have to worry about it. It goes dormant until it receives a notification. Except for the fact that it keeps an OS thread occupied it is entirely out of play.
This is why using notifyAll is less than ideal, it causes a bunch of threads that were previously happily dormant putting no load on the system to get woken up, where most of them will block until they can acquire the lock, find the condition they are waiting for is not true, and go back to waiting. It would be preferable to notify only those threads that have a chance of making progress.
(Using ReentrantLock instead of intrinsic locks allows you to have multiple conditions for one lock, so that you can make sure the notified thread is one that's waiting on a particular condition, avoiding the lost-notification bug in the case of a thread getting notified for something it can't act on.)
This is the answer to the question about how to switch the thread state in Java. I hope the above content can be of some help to you. If you still have a lot of doubts to solve, you can follow the industry information channel to learn more about it.
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.