Several states of the Java_ thread

Source: Internet
Author: User

There are several states in the Java Thread's run cycle, which are defined and explained in detail in Java.lang.Thread.State:

The NEW state is the line Cheng Gang created, not yet started

RUNNABLE State is the thread is working properly, of course, there may be some time-consuming calculation/io wait for the operation of/cpu and so on, this state of the wait is usually other system resources, rather than locks, sleep, etc.

BLOCKEDIn this state, there are scenarios in which multiple threads have synchronous operations, such as the execution of a synchronized block waiting for another thread, or a reentrant synchronized block in which someone calls the wait () method, where the thread is waiting to enter the critical section.

waiting This state refers to a thread that has a lock, calls his wait method, waits for another thread/lock owner to call Notify/notifyall once the thread can proceed to the next step, which distinguishes between BLOCKED and wating The difference is that one is waiting outside the critical point, one is waiting for others to notify in the understanding points, and the thread calls the Join method to join the other thread, and it goes into the waiting state, waiting for the thread to be executed by his join.

timed_waiting This state is a limited (time-limited) waiting, which generally occurs when a call to wait (long), join (long), and so on, the other thread will enter the Timed_ after sleep. Waiting status

TERMINATED This state indicates that the thread's Run method has been executed and is basically dead (if the thread is persisted, it may not be recycled)

Let's talk about how to get threads into the above states: 1. NEW, this is the simplest, Static voidNEW () {Thread T = NewThread (); System. out. println (T.getstate ()); } Outputs new 2. RUNNABLE, also simple, let a thread start, while the code inside do not sleep or wait wait, etc. Private Static voidRUNNABLE () {Thread T = NewThread () { Public voidRun () { for( inti=0; I<integer. Max_value; i++) {System. out. println (i);                  }             }                      };    T.start (); } 3. BLOCKED, this must be at least two threads above, and then wait for each other synchronized block Private Static voidBLOCKED () { FinalObject lock = NewObject (); Runnable Run = NewRunnable () {@Override Public voidRun () { for( inti=0; I<integer. Max_value; i++) { synchronized(lock) {System. out. println (i);                  }                                       }             }         }; Thread T1 = NewThread (run);         T1.setname ("T1″"); Thread t2 = NewThread (run);                  T2.setname ("T2″");         T1.start ();             T2.start (); At this time, one in runnable, the other in blocked (waiting for another thread of System.out.println: This is an IO operation, belongs to system resources, does not cause waiting, etc.) 4. Waiting, this needs to be used in the producer consumer model, and when producers are slow, consumers wait for the next notify of producers Private Static voidWaiting () { FinalObject lock = NewObject (); Thread T1 = NewThread () {@Override Public voidRun () { inti = 0; while( true){ synchronized(lock) { Try{lock.wait (); } Catch(Interruptedexception e) {} System. out. println (i++);                  }                 }             }         }; Thread t2 = NewThread () {@Override Public voidRun () { while( true){ synchronized(lock) { for( inti = 0; i< 10000000; i++) {System. out. println (i);                           }                            Lock.notifyall ();                       }                                         }              }         };                   t1.setname (  "^^ t1^^ ");    &nBsp;     t2.setname (  "^^ t2^^");                   t1.start ();          t2.start ();    }   5.  timed_waiting, this only needs to be on the basis of 4, the Wait method plus a time parameter to limit is OK. Change the synchronized block in 4 to the following. synchronized(lock) { Try{lock.wait (1000L); } Catch(Interruptedexception e) {} System. out. println (i++); Another look at the output of the stack, called timed_waiting (on object monitor), shows that there are other things behind the brackets, such as sleep, and we'll just change the T2 for loop to sleep: synchronized(lock) {
Try{ Sleep(30*1000l); } Catch(Interruptedexception e)  {} lock.notifyall ();} See, T2 's state is timed_waiting (sleeping), and T1 is still on object monitor, because T1 or wait is waiting for T2 notify, and T2 is its own sleep in addition, the join operation is also entered on Object Monitor 6. TERMINATED, this state, as long as the thread ends the Run method, it will enter ... Private Static voidTERMINATED () {Thread T1 = NewThread ();         T1.start (); System. out. println (T1.getstate ()); Try{Thread. Sleep(1000L); } Catch(Interruptedexception e) {} System. out. println (T1.getstate ()); } output: Runnableterminated because the Start method of the thread is started asynchronously, it is possible to get the state immediately after it is executed and it has not been executed so much nonsense. understand what a thread's state really is? So this is a fishing stick ... Well, in a word, there's a potential performance bottleneck in finding the system. When the Java system is running slowly, we should first find the bottleneck of performance, and JstackTools such as the current stack of the JVM can see the state of all threads of the current entire VM, when we see a thread state is often in waiting or blocked, be careful, he may be waiting for resources are often not released (of course, Thread pool scheduling is also a variety of queue locks, to distinguish between, for example, this is a classic concurrent package inside the thread pool, its scheduling queue is Linkedblockingqueue, the execution takes when the block, waiting for the next task into the queue, and then into the execution, This theory is not a system of performance bottlenecks, to find bottlenecks in general Find your own code first.Stack and then we'll check out those open source components./JDK: 0. How do I track a thread? See the above stack output no, the first line is the content is threadname priority tid nid desc more than tracking tid, nid can only find the thread. 1. The discovery of a wired path into the block, and lasted for a long time, this indicates that the performance bottleneck exists in the synchronized block, because he has been block live, can't get in, the other thread has not been processed, and this synchronized block processing speed is relatively slow, And then look deeper. Of course, it is also possible to block too many threads at the same time, queuing too long caused. 2. Discover that the thread has entered the waiting for a long time, indicating that the performance bottleneck exists in the logic that triggered the notify. Of course, there are too many threads waiting at the same time, always waiting to be released.  3. Thread enters time_waiting state and lasts for a long time, same as 2 troubleshooting. The above black and white are printed through jstack, you can directly navigate to the thread you want to know the execution stack, which has a great effect on the Java performance bottleneck analysis.

Several states of the Java_ thread

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.