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)05/31 Report--
In this article, the editor introduces in detail "what are the six states and life cycle of Java threads". The content is detailed, the steps are clear, and the details are handled properly. I hope this article "what are the six states and life cycle of Java threads" can help you solve your doubts.
1. Thread state (lifecycle)
A thread can only be in one state at a given point in time.
Threads can have the following six states:
New (newly created): unstarted thread
Runnable: runnable threads that need to wait for operating system resources
Blocked (blocked): a thread that is blocked while waiting for a monitor lock
Waiting: waits for the wake-up state, waiting indefinitely for another thread to wake up
Timed waiting (timed wait): a thread that waits for another thread to perform an operation within a specified wait time
Terminated (terminated): the thread that exited.
To determine the current state of a thread, call the getState method
Thread state diagram
Note: the state of the dotted frame (in all uppercase English) is the Java thread state.
two。 Operation thread status 2.1. Newly created status (NEW)
This is the state of the unstarted thread after the instantiated thread is completed.
You can create threads in three ways
Override the Thread class run () method
Implement the Runnable interface
Implement the Callable interface
A simple example summarizes three ways
Public class Demo {public static void main (String [] args) throws ExecutionException, InterruptedException {/ * * 1. Directly override run () or inherit the Thread class and then rewrite run () * / Thread thread = new Thread () {@ Override public void run () {System.out.println ("Thread");}}; / / start thread thread.start () / * 2.lambda, inner class or thread class to implement the Runnable interface, implement the run () method * and then give it to the Thread class * / Thread runThread = new Thread (()-> {System.out.println ("Runnable");}); / / Open thread runThread.start () / * 3.lambda, inner class or thread class implements the Callable interface, implements the call () method * and then gives it to the Thread class: FutureTask is also a Runnable implementation class * / FutureTask futureTask = new FutureTask (()-> {System.out.println ("Callable"); return "CallableThread";}); Thread callThread = new Thread (futureTask) / / start thread callThread.start (); / / get the return value of the call () method String s = futureTask.get (); System.out.println ("return value of the call () method:" + s);}}
It doesn't make sense to instantiate a thread created by the Thread class directly without overriding the run () or call () method.
Only threads created in Callable mode can get the return value of the thread.
2.2. Operational status (RUNNABLE)
This state refers to the state that the thread instantiated object enters after calling the start () method. The thread is in a runnable state and can execute the program if there are resources such as a processor.
At the operating system level, this state consists of two steps: thread ready and thread running, but in Java thread state, both steps are collectively referred to as Runnable (runnable) states.
The thread changes from the ready state to the running state, depending on whether your thread has grabbed the CPU resources (CPU time slice). Whoever gets it will run, and wait if you don't get it. Because the CPU time slice (execution time) is very short, about ten milliseconds, so the time for thread switching is very short, and the time for the ready state to become running state is also very short, and the change in this state can hardly be felt during development, so the two are regarded as a whole in Java, focusing on whether threads can run and differ from other states, which further simplifies thread development. If your program has to run for a long time (such as writing an endless loop) and does not finish in a CPU time slice, then your thread will grab the next CPU time slice and continue to execute the program until the program in the thread is finished.
In fact, this scenario should have been seen before. For example, when multiple threads execute the same program and all print logs to the same file, the logs of different threads will be mixed together, which is not conducive to troubleshooting. The common ways to solve this problem are: one is to print the log to different files in different threads; the other is to save the log information to the string object and print the log information to the file at the end of the program. The second way is to use a time slice of CPU to print the log information.
Note: the program can only call the start () method on threads in a new state, and do not call the start () method on threads in a non-new state, which will throw an IllegalThreadStateException exception.
2.3. Blocked state (BLOCKED)
The thread is in a blocked state waiting for the monitor lock. One thread acquired the lock that was not released, and other threads came to acquire it, but found that they could not acquire the lock and entered a blocked state.
The blocked state exists only under multi-thread concurrent access, which is different from the latter two kinds of blocking caused by the thread entering "waiting" by itself.
Enter the state
Enter the synchronized code block / method
The lock was not acquired
Exit statu
Get the monitor lock
2.4. Wait for Wake up status (WAITING)
The whole process is like this: a thread first acquires an object lock in an object's synchronization method; when executing the wait method, the thread releases the object lock and the thread is placed in the object's waiting queue; waits for another thread to acquire the lock of the same object, and then wakes up the thread in the object waiting queue with the notify () or notifyAll () method.
You can know from the whole process.
The wait (), notify (), and notifyAll () methods need to be executed after the thread acquires the lock, so all three methods need to be executed in a synchronous code block / method, otherwise an exception is reported: java.lang.IllegalMonitorStateException.
In the synchronous code block, when a thread enters the WAITING state, the lock is released without causing the thread to block. On the other hand, if the lock is not released, other threads will not be able to acquire the lock and wake it up.
Enter the state
Object.wait ()
Thread.join ()
LockSupport.park ()
Exit statu
Object.notify ()
Object.notifyall ()
LockSupport.unpark ()
2.5. Timing wait status (TIMED_WAITING)
Generally, when the timing ends, the thread will automatically wake up to continue to execute the following program. For the Object.wait (long) method, you can also take the initiative to notify wake-up.
Note: the sleep () method under the Thread class can be executed anywhere; the wait (long) method, like the wait () method, needs to be executed in a synchronous code block / method, otherwise an exception is reported: java.lang.IllegalMonitorStateException.
Enter the state
Thread.sleep (long)
Object.wait (long)
Thread.join (long)
LockSupport.parkNanos (long)
LockSupport.parkNanos (Object blocker, long nanos)
LockSupport.parkUntil (long)
LockSupport.parkUntil (Object blocker, long deadline)
Note: the blocker parameter is the synchronization object responsible for hosting this thread.
Exit statu
The timing ends.
LockSupport.unpark (Thread)
Object.notify ()
Object.notifyall ()
2.6. Termination (TERMINATED)
Thread execution end
Run () / call () execution completed
Stop () thread
Error or exception > accidental death
The stop () method has been deprecated.
3. View the 6 states of a thread
Use a simple example to see the six states that a thread appears.
Case
Public class Demo3 {private static Object object = "obj"; public static void main (String [] args) throws InterruptedException {Thread thread0 = new Thread (()-> {try {/ / blocked state (BLOCKED) synchronized (object) {System.out.println ("thread0 entry: waiting to wake up state (WAITING)") Object.wait (); System.out.println ("thread0 released: waking up status (WAITING)");} System.out.println ("thread0" + Thread.currentThread (). GetState ());} catch (InterruptedException e) {e.printStackTrace ();}}) / / newly created status (NEW) System.out.println (thread0.getName () + ":" + thread0.getState ()); Thread thread1 = new Thread (()-> {try {System.out.println ("thread1 entry: timing waiting status (TIMED_WAITING)"); Thread.sleep (2) System.out.println ("thread1 out: timing wait status (TIMED_WAITING)");} catch (InterruptedException e) {e.printStackTrace ();} / blocked status (BLOCKED) synchronized (object) {System.out.println ("thread1 release: waiting for Wake up status (WAITING)") Object.notify (); System.out.println ("thread1 release completed: waiting for Wake up status (WAITING)");} System.out.println ("thread1" + Thread.currentThread (). GetState ();}); / / newly created status (NEW) System.out.println (thread1.getName () + ":" + thread1.getState ()) PrintState (thread0); printState (thread1); / / RUNNABLE thread0.start (); / / RUNNABLE thread1.start () } / / use separate threads to print thread status private static void printState (Thread thread) {new Thread (()-> {while (true) {System.out.println (thread () + ":" + thread.getState () If (thread.getState (). Equals (Thread.State.TERMINATED)) {System.out.println (thread.getName () + ":" + thread.getState ()); break;}) .start ();}}
Execution result: simplified output result
Thread-0:NEW
Thread-1:NEW
Thread-0:RUNNABLE
Thread-1:RUNNABLE
Thread0 entry: waiting for wake-up status (WAITING)
Thread-1:BLOCKED
Thread1 entry: timing wait status (TIMED_WAITING)
Thread-0:BLOCKED
Thread-0:WAITING
……
Thread-0:WAITING
Thread-1:BLOCKED
Thread-1:TIMED_WAITING
……
Thread-1:TIMED_WAITING
Thread-1:BLOCKED
……
Thread-1:BLOCKED
Thread-0:WAITING
……
Thread-0:WAITING
Thread1 out: timing wait status (TIMED_WAITING)
Thread-0:WAITING
Thread-1:BLOCKED
Thread1 release: waiting for wake-up status (WAITING)
Thread-1:BLOCKED
Thread-0:WAITING
Thread-0:BLOCKED
Thread1 release completed: waiting for wake-up status (WAITING)
Thread-1:BLOCKED
Thread1 RUNNABLE
Thread-0:BLOCKED
Thread-1:TERMINATED
Thread0 undone: waiting for wake-up status (WAITING)
Thread-0:BLOCKED
Thread0 RUNNABLE
Thread-0:TERMINATED
The final implementation result is shown in the figure.
Note: because separate threads are used in the case to print the status of different threads, there will be a slight delay in status printing.
After reading this, the article "what are the six states and lifecycles of Java threads" has been introduced. If you want to master the knowledge points of this article, you still need to practice and use it yourself. If you want to know more about related articles, welcome to follow the industry information channel.
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.