Java Thread State Analysis

Source: Internet
Author: User
Tags thread class

There are several states in the life cycle of a Java thread. In the thread class, there is an enumeration type state, which defines several states of a thread, respectively:

    1. NEW: After the thread was created, but not yet started (not yet started). It's the state of new.
    2. RUNNABLE: The state of the thread that is running the task under the Java Virtual machine. A thread in the runnable state may be in a wait state because it is waiting for some system resources to be released, such as IO
    3. BLOCKED: Blocking state, waiting for the release of the lock, such as thread A into a synchronized method, thread B also wants to enter this method, but the lock of this method has been obtained by thread A, this time thread B is in the BLOCKED state
    4. Waiting: Wait state, the thread in the waiting state is due to the execution of any of the 3 methods. 1. The wait method for object and does not use the timeout parameter; 2. Thread's Join method does not use the timeout parameter 3. Locksupport's Park method. A thread in the waiting state waits for another thread to handle a particular behavior. For example, if a thread invokes the wait method for an object, the thread will be in the waiting state until another thread calls the object's notify or Notifyall method to dismiss the state.
    5. Timed_waiting: There is a wait state for waiting time, such as calling any of the following methods, and specifying the wait time, the thread will be in this state. 1. Thread.Sleep Method 2. The wait method for object, with time 3. Thread.Join method, with time 4. Locksupport's Parknanos method, with time 5. Parkuntil method of Locksupport, with time
    6. TERMINATED: Thread aborted state, this thread has performed its task completely

Here are some examples of how a thread will be in these states:

New state

The new state is relatively simple, after instantiating a thread, and the thread does not start executing, this time the state is new:

Thread thread = new Thread();System.out.println(thread.getState()); // NEW
runnable status

The state that is running.

Thread thread = new Thread(new Runnable() {    @Override    public void run() {        for(int i = 0; i < Integer.MAX_VALUE; i ++) {            System.out.println(i);        }    }}, "RUNNABLE-Thread");thread.start();

To view thread status using Jstack:

"Runnable-thread" #10 prio=5 os_prio=31 tid=0x00007f8e04981000 nid=0x4f03 RUNNABLE [0x000070000124c000] Java.lang.Thread.State:RUNNABLE at Java.io.FileOutputStream.writeBytes (Native Method) at Java.io.FileOutputStream.write (fileoutputstream.java:315) at Java.io.BufferedOutputStream.flushBuffer ( bufferedoutputstream.java:82) at Java.io.BufferedOutputStream.flush (bufferedoutputstream.java:140)-Locked < 0x000000079764cc50> (a Java.io.BufferedOutputStream) at Java.io.PrintStream.write (printstream.java:482)-Locked & Lt;0x0000000797604dc0> (a Java.io.PrintStream) at Sun.nio.cs.StreamEncoder.writeBytes (streamencoder.java:221) at Sun.nio.cs.StreamEncoder.implFlushBuffer (streamencoder.java:291) at Sun.nio.cs.StreamEncoder.flushBuffer ( streamencoder.java:104)-Locked <0x0000000797604d78> (a java.io.OutputStreamWriter) at Java.io.OutputStreamWriter.flushBuffer (outputstreamwriter.java:185) at Java.io.PrintStream.write ( printstream.java:527)-Eliminated <0x0000000797604dc0> (a Java.io.PrintStream) at Java.io.PrintStream.print (printstream.java:597) at Java.io.PrintStream.println (printstream.java:736)-Locked <0x0000000797604dc0> (a java.io.PrintStream) at Study.thread.threadstatetest$1.run (threadstatetest.java:23) at Java.lang.Thread.run (thread.java:745)
Blocked status

Both thread A and thread B need to hold locks on the lock object to invoke the method. If thread A holds a lock, thread B is in the blocked state, and if thread B holds the lock, thread A is in the blocked state. Examples of using the Thread.Sleep method are mainly for debugging convenience:

final Object lock = new Object();Thread threadA = new Thread(new Runnable() {    @Override    public void run() {        synchronized (lock) {            System.out.println(Thread.currentThread().getName() + " invoke");            try {                Thread.sleep(20000l);            } catch (InterruptedException e) {                e.printStackTrace();            }        }    }}, "BLOCKED-Thread-A");Thread threadB = new Thread(new Runnable() {    @Override    public void run() {        synchronized (lock) {            System.out.println(Thread.currentThread().getName() + " invoke");            try {                Thread.sleep(20000l);            } catch (InterruptedException e) {                e.printStackTrace();            }        }    }}, "BLOCKED-Thread-B");threadA.start();threadB.start();

Use Jstack to view thread status. Thread A is in the timed_waiting state and thread B is in the blocked state because thread a executes after thread B executes and after thread a executes and calls the Thread.Sleep method:

"BLOCKED-Thread-B" #11 prio=5 os_prio=31 tid=0x00007fa7db8ff000 nid=0x5103 waiting for monitor entry [0x000070000134f000]   java.lang.Thread.State: BLOCKED (on object monitor)  at study.thread.ThreadStateTest$3.run(ThreadStateTest.java:50)  - waiting to lock <0x0000000795a03bf8> (a java.lang.Object)  at java.lang.Thread.run(Thread.java:745)"BLOCKED-Thread-A" #10 prio=5 os_prio=31 tid=0x00007fa7db15a000 nid=0x4f03 waiting on condition [0x000070000124c000]   java.lang.Thread.State: TIMED_WAITING (sleeping)  at java.lang.Thread.sleep(Native Method)  at study.thread.ThreadStateTest$2.run(ThreadStateTest.java:39)  - locked <0x0000000795a03bf8> (a java.lang.Object)  at java.lang.Thread.run(Thread.java:745)
Waiting status

The wait method for object, the join method for thread, and the await method of Conditon all produce the waiting state.

1. The wait method for an object without a time parameter

final Object lock = new Object();Thread threadA = new Thread(new Runnable() {    @Override    public void run() {        synchronized (lock) {            try {                lock.wait();                System.out.println("wait over");            } catch (InterruptedException e) {                e.printStackTrace();            }        }    }}, "WAITING-Thread-A");Thread threadB = new Thread(new Runnable() {    @Override    public void run() {        synchronized (lock) {            try {                Thread.sleep(20000);            } catch (InterruptedException e) {                e.printStackTrace();            }            lock.notifyAll();        }    }}, "WAITING-Thread-B");threadA.start();threadB.start();

Waiting-thread-a called the lock's Wait, which is in the waiting state:

"WAITING-Thread-B" #11 prio=5 os_prio=31 tid=0x00007f8de992d800 nid=0x5103 waiting on condition [0x000070000134f000]   java.lang.Thread.State: TIMED_WAITING (sleeping)  at java.lang.Thread.sleep(Native Method)  at study.thread.ThreadStateTest$5.run(ThreadStateTest.java:84)  - locked <0x0000000795a03e40> (a java.lang.Object)  at java.lang.Thread.run(Thread.java:745)"WAITING-Thread-A" #10 prio=5 os_prio=31 tid=0x00007f8dea193000 nid=0x4f03 in Object.wait() [0x000070000124c000]   java.lang.Thread.State: WAITING (on object monitor)  at java.lang.Object.wait(Native Method)  - waiting on <0x0000000795a03e40> (a java.lang.Object)  at java.lang.Object.wait(Object.java:502)  at study.thread.ThreadStateTest$4.run(ThreadStateTest.java:71)  - locked <0x0000000795a03e40> (a java.lang.Object)  at java.lang.Thread.run(Thread.java:745)

The Join method for 2.Thread

Thread threadA = new Thread(new Runnable() {    @Override    public void run() {        try {            Thread.sleep(20000);        } catch (InterruptedException e) {            e.printStackTrace();        }        System.out.println("Thread-A over");    }}, "WAITING-Thread-A");threadA.start();try {    threadA.join();} catch (InterruptedException e) {    e.printStackTrace();}

Main thread main is in waiting state:

"Waiting-thread-a" #10 prio=5 os_prio=31 tid=0x00007fd2d5100000 nid=0x4e03 waiting on condition [0x000070000124c000] Jav A.lang.thread.state:timed_waiting (sleeping) at Java.lang.Thread.sleep (Native Method) at Study.thread.threadstatetest$6.run (threadstatetest.java:103) at Java.lang.Thread.run (thread.java:745) "main" #1 Prio=5 os_prio=31 tid=0x00007fd2d3815000 nid=0x1003 in object.wait () [0x0000700000182000] Java.lang.Thread.State: Waiting (on object monitor) at java.lang.Object.wait (Native Method)-Waiting on <0x0000000795a03ec0> (a Java.lang . Thread) at Java.lang.Thread.join (thread.java:1245) – Locked <0x0000000795a03ec0> (a java.lang.Thread) at Java.lan G.thread.join (thread.java:1319) at Study.thread.ThreadStateTest.WAITING_join (threadstatetest.java:118) at Study.thread.ThreadStateTest.main (threadstatetest.java:13) at Sun.reflect.NativeMethodAccessorImpl.invoke0 ( Native Method) at Sun.reflect.NativeMethodAccessorImpl.invoke (nativemethodaccessorimpl.java:62) At Sun.reflect.DelegatingMethodAccessorImpl.invoke (delegatingmethodaccessorimpl.java:43) at Java.lang.reflect.Method.invoke (method.java:483) at Com.intellij.rt.execution.application.AppMain.main ( appmain.java:140)

3. Await method for condition without time parameters

Condition's await method is the same as Obejct's wait method principle, so it is also waiting state

Timed_waiting status

The timed_waiting state is similar to the timeing state, which is a waiting state with waiting time and will not be waiting.

The simplest example of a timed_waiting state is the sleep method of thread:

Thread threadA = new Thread(new Runnable() {    @Override    public void run() {        try {            Thread.sleep(20000);        } catch (InterruptedException e) {            e.printStackTrace();        }        System.out.println("Thread-A over");    }}, "WAITING-Thread-A");threadA.start();try {    Thread.sleep(5000);} catch (InterruptedException e) {    e.printStackTrace();}System.out.println(threadA.getState()); // TIMED_WAITING

Or the Wait method for object with the time parameter, the thread's join method with the time parameter also causes the thread's state to be in the timed_waiting state.

TERMINATED

The state of the thread termination, the completion of the thread execution, and the end of the life cycle.

Thread threadA = new Thread();threadA.start();try {    Thread.sleep(5000l);} catch (InterruptedException e) {    e.printStackTrace();}System.out.println(threadA.getState()); // TERMINATED
Summarize

Understanding the state of a thread can analyze some problems.

For example, the thread is in the blocked state, this time can be analyzed is not lock lock when you forget to release, or release the wrong time. Causes another thread to remain in the blocked state.

For example, the thread is in the waiting state, this time can analyze the Notifyall or Signalall method call timing is not right.

Java's own Jstack tool can analyze specific information such as the status, priority, and description of the thread.

Java Thread State Analysis

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.