Several states of Java threads

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.

BLOCKED This state is a scenario in which multiple threads have synchronous operations, such as the execution of a synchronized block that is waiting for another thread, or a reentrant synchronized block in which someone calls the wait () method, This is where the thread waits 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 these states:


1. NEW, this is the simplest,

Static void NEW () {

Thread T = new thread ();

System. out. println (T.getstate ());

}

Output new

2. RUNNABLE, also simple, let a thread start, while the code does not sleep or wait wait, etc.

Private Static void RUNNABLE () {

Thread T = new thread () {

Public void Run () {

for (int i=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 synchronized blocks to each other

Private Static void BLOCKED () {

Final Object lock = New object ();

Runnable run = new Runnable () {

@Override

Public void Run () {

for (int i=0; I<integer. Max_value; i++) {

synchronized (lock) {

System. out. println (i);

}

}

}

};

Thread T1 = new thread (run);

T1.setname ("T1");

Thread t2 = New thread (run);

T2.setname ("T2");

T1.start ();

T2.start ();

}

At this time, one in runnable, the other in blocked (waiting for the System.out.println of another thread: this is an IO operation, is a system resource, does not cause waiting, etc.)

4. waiting, this needs to use the producer consumer model, when the producer is slow, the consumer waits for the producer's next notify

Private Static void Waiting () {

Final Object lock = New object ();

Thread T1 = new thread () {

@Override

Public void Run () {

int i = 0;

while (true ) {

synchronized (lock) {

Try {

Lock.wait ();

} catch (Interruptedexception e) {

}

System. out. println (i++);

}

}

}

};

Thread t2 = new thread () {

@Override

Public void Run () {

while (true ) {

synchronized (lock) {

for (int i = 0; i< 10000000; i++) {

System. out. println (i);

}

Lock.notifyall ();

}

}

}

};

T1.setname ("^^ t1^^");

T2.setname ("^^ t2^^");

T1.start ();

T2.start ();

}

5. timed_waiting, this is only required 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++);

}

Also look at the output of the stack, his name is timed_waiting (on object monitor), there are other things behind the brackets, such as sleep, we directly change the T2 for loop to sleep test:

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 his own sleep

In addition, the join operation also enters on object monitor

6. TERMINATED, this status as long as the thread ends the Run method, it will enter ...

Private Static void TERMINATED () {

Thread T1 = new thread ();

T1.start ();

System. out. println (T1.getstate ());

Try {

Thread. Sleep (1000L);

} catch (Interruptedexception e) {

}

System. out. println (T1.getstate ());

}

Output:

RUNNABLE

TERMINATED

Since the thread's Start method is started asynchronously, it is possible to get the state immediately after it has been executed and has not yet finished executing the Run method

So much nonsense, what's the use of knowing the state of a thread ?

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 Jstack and other tools, through the JVM current stack can see the current entire VM All threads state, 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, the thread pool Scheduler 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 with Linkedblockingqueue, the execution take when the block, waiting for the next task into the queue, and then into the execution, this theory is not a system performance bottleneck, looking for bottlenecks in general Find your own code stack first , and then troubleshoot open source Components /jdk.

Several ways to troubleshoot problems:

0. How do I keep track of a thread?

See above the stack output no, the first line is the content is threadname priority tid nid desc

More than tracing the 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.

Note: All of the above code is written in order to track the status of the thread, so do not write it in the app online ...

Several states of Java threads

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.