Several state of the thread charm 4. Java concurrent programming

Several state of the thread charm Java concurrent programming

1.1 thread state

The above procedure if you look carefully, you will find that I not only print the ID of the thread, also print the name of the execution state of the thread.

Java threads running life cycle may be in six different states as shown in the following table,

In a given moment, the thread can only be in one of them.

State Name Explanation
NEW The initial state, the thread is constructed, but also not called start () method
RUNNABLE Operating status, Java threads in the operating system is ready and running two states collectively operation.
BLOCKED Blocking state, it indicates that the thread blocked on lock
WAITING Wait state, it indicates that the thread in a wait state, entering the state indicates that the current thread to wait for another thread to make some specific action (notification or interrupt)
TIME_WAITING Timeout wait state, which is different from the WAITING state, it is free to return at a specified time.
TERMINATED Termination state, indicates that the current thread has finished

1.2 thread state example

Next we write down an example to emulate

import java.lang.management.ManagementFactory;
import java.lang.management.ThreadInfo;
import java.lang.management.ThreadMXBean;
import java.util.concurrent.TimeUnit;

/**
 * @author qing-feng.zhao
 * @功能 线程的状态
 * @时间 2019/12/19 14:58
 */
public class ThreadState {
    public static void main(String[] args) {
        //模拟一个TIMED_WAITING 状态的线程  一直休眠状态的线程
        new Thread(new TimeWaiting(),"TimeWaitingThread").start();
        //模拟一个WAITING 状态的线程  一直等待状态线程
        new Thread(new Waiting(),"WaitingHead").start();
        //模拟两个线程,一个处于BLOCKED状态的线程,一个处于TIMED_WAITING状态的线程
        new Thread(new Blocked(),"BlockedThread-1").start();
        new Thread(new Blocked(),"BlockedThread-2").start();

        //显示线程的执行状态
        showThreadInfo();
    }

    /**
     * 该线程不断地进行睡眠,比如懒洋洋
     */
    static class TimeWaiting implements Runnable{
        @Override
        public void run() {
            while (true){
                try {
                    TimeUnit.SECONDS.sleep(100);
                } catch (InterruptedException e) {
                    System.err.println("休眠出错:"+e);
                }
            }
        }
    }

    /**
     * 该线程不断地进行等待
     * 锁住当前Waiting.class
     */
    static class Waiting implements Runnable{

        @Override
        public void run() {
            //一直等待
            while(true){
                synchronized (Waiting.class){
                    try {
                        Waiting.class.wait();
                    } catch (InterruptedException e) {
                        System.err.println("线程等待异常:"+e);
                    }
                }
            }
        }
    }

    /**
     * 该线程在Blocked.class 实例上加锁后,不会释放锁
     */
    static class Blocked implements Runnable{

        @Override
        public void run() {
            //获取锁
            synchronized (Blocked.class){
                //一直睡觉不释放锁
                while (true){
                    try {
                        TimeUnit.SECONDS.sleep(100);
                    } catch (InterruptedException e) {
                        System.err.println("休眠出错:"+e);
                    }
                }
            }
        }
    }

    private static void showThreadInfo(){
        //获取Java线程管理MXBean
        ThreadMXBean threadMXBean= ManagementFactory.getThreadMXBean();

        //不需要获取同步的monitor和 synchronized 信息,仅获取线程和线程堆栈信息
        ThreadInfo[] threadInfoArray=threadMXBean.dumpAllThreads(true,true);

        //遍历线程信息,仅打印线程ID 和线程名称信息
        for (ThreadInfo threadInfo:threadInfoArray
        ) {
            System.out.println("["+threadInfo.getThreadId()+"]"+threadInfo.getThreadName()+"["+threadInfo.getThreadState()+"]");
        }
    }
}

Output:

[14]BlockedThread-2[BLOCKED]
[13]BlockedThread-1[TIMED_WAITING]
[12]WaitingHead[WAITING]
[11]TimeWaitingThread[TIMED_WAITING]
[6]Monitor Ctrl-Break[RUNNABLE]
[5]Attach Listener[RUNNABLE]
[4]Signal Dispatcher[RUNNABLE]
[3]Finalizer[WAITING]
[2]Reference Handler[WAITING]
[1]main[RUNNABLE]

Of course, there is a way, we enter the following command to display the currently running process java

jps -l 

Outputting content as follows:

8080 sun.tools.jps.jps 
1848 com.xingyun.main.ThreadState

We can draw the current program process ID is 1848,

Enter the following command to view details

jstack 1848

Output as follows:

mixed mode):

"DestroyJavaVM" #15 prio=5 os_prio=0 tid=0x0000000002398000 nid=0x2468
waiting on condition [0x0000000000000000]    java.lang.Thread.State:
RUNNABLE

"BlockedThread-2" #14 prio=5 os_prio=0 tid=0x0000000058c5d000
nid=0x2540 waiting for monitor entry [0x000000005a34f000]   
java.lang.Thread.State: BLOCKED (on object monitor)
        at com.xingyun.main.ThreadState$Blocked.run(ThreadState.java:89)
        - waiting to lock <0x00000000d57263c8> (a java.lang.Class for com.xingyun.main.ThreadState$Blocked)
        at java.lang.Thread.run(Thread.java:748)

"BlockedThread-1" #13 prio=5 os_prio=0 tid=0x0000000058c5a000
nid=0x24e4 waiting on condition [0x000000005a15f000]   
java.lang.Thread.State: TIMED_WAITING (sleeping)
        at java.lang.Thread.sleep(Native Method)
        at java.lang.Thread.sleep(Thread.java:340)
        at java.util.concurrent.TimeUnit.sleep(TimeUnit.java:386)
        at com.xingyun.main.ThreadState$Blocked.run(ThreadState.java:89)
        - locked <0x00000000d57263c8> (a java.lang.Class for com.xingyun.main.ThreadState$Blocked)
        at java.lang.Thread.run(Thread.java:748)

"WaitingHead" #12 prio=5 os_prio=0 tid=0x0000000058c52000 nid=0x1c90
in Object.wait() [0x0000000059f2f000]    java.lang.Thread.State:
WAITING (on object monitor)
        at java.lang.Object.wait(Native Method)
        - waiting on <0x00000000d5722c28> (a java.lang.Class for com.xingyun.main.ThreadState$Waiting)
        at java.lang.Object.wait(Object.java:502)
        at com.xingyun.main.ThreadState$Waiting.run(ThreadState.java:68)
        - locked <0x00000000d5722c28> (a java.lang.Class for com.xingyun.main.ThreadState$Waiting)
        at java.lang.Thread.run(Thread.java:748)

"TimeWaitingThread" #11 prio=5 os_prio=0 tid=0x0000000058c51800
nid=0x27e0 waiting on condition [0x0000000059c2e000]   
java.lang.Thread.State: TIMED_WAITING (sleeping)
        at java.lang.Thread.sleep(Native Method)
        at java.lang.Thread.sleep(Thread.java:340)
        at java.util.concurrent.TimeUnit.sleep(TimeUnit.java:386)
        at com.xingyun.main.ThreadState$TimeWaiting.run(ThreadState.java:48)
        at java.lang.Thread.run(Thread.java:748)

"Service Thread" #10 daemon prio=9 os_prio=0 tid=0x0000000058b74000
nid=0x2524 runnable [0x0000000000000000]    java.lang.Thread.State:
RUNNABLE

"C1 CompilerThread2" #9 daemon prio=9 os_prio=2 tid=0x0000000058ae6000
nid=0x1804 waiting on condition [0x0000000000000000]   
java.lang.Thread.State: RUNNABLE

"C2 CompilerThread1" #8 daemon prio=9 os_prio=2 tid=0x0000000058ac9000
nid=0x269c waiting on condition [0x0000000000000000]   
java.lang.Thread.State: RUNNABLE

"C2 CompilerThread0" #7 daemon prio=9 os_prio=2 tid=0x0000000058a9d000
nid=0x2568 waiting on condition [0x0000000000000000]   
java.lang.Thread.State: RUNNABLE

"Monitor Ctrl-Break" #6 daemon prio=5 os_prio=0 tid=0x0000000058add000
nid=0x1514 runnable [0x000000005913e000]    java.lang.Thread.State:
RUNNABLE
        at java.net.SocketInputStream.socketRead0(Native Method)
        at java.net.SocketInputStream.socketRead(SocketInputStream.java:116)
        at java.net.SocketInputStream.read(SocketInputStream.java:171)
        at java.net.SocketInputStream.read(SocketInputStream.java:141)
        at sun.nio.cs.StreamDecoder.readBytes(StreamDecoder.java:284)
        at sun.nio.cs.StreamDecoder.implRead(StreamDecoder.java:326)
        at sun.nio.cs.StreamDecoder.read(StreamDecoder.java:178)
        - locked <0x00000000d57b3d28> (a java.io.InputStreamReader)
        at java.io.InputStreamReader.read(InputStreamReader.java:184)
        at java.io.BufferedReader.fill(BufferedReader.java:161)
        at java.io.BufferedReader.readLine(BufferedReader.java:324)
        - locked <0x00000000d57b3d28> (a java.io.InputStreamReader)
        at java.io.BufferedReader.readLine(BufferedReader.java:389)
        at com.intellij.rt.execution.application.AppMainV2$1.run(AppMainV2.java:64)

"Attach Listener" #5 daemon prio=5 os_prio=2 tid=0x0000000058a7b000
nid=0x2448 waiting on condition [0x0000000000000000]   
java.lang.Thread.State: RUNNABLE

"Signal Dispatcher" #4 daemon prio=9 os_prio=2 tid=0x000000005762a800
nid=0x2650 runnable [0x0000000000000000]    java.lang.Thread.State:
RUNNABLE

"Finalizer" #3 daemon prio=8 os_prio=1 tid=0x000000005760a800
nid=0x2620 in Object.wait() [0x000000005896f000]   
java.lang.Thread.State: WAITING (on object monitor)
        at java.lang.Object.wait(Native Method)
        - waiting on <0x00000000d5588ec8> (a java.lang.ref.ReferenceQueue$Lock)
        at java.lang.ref.ReferenceQueue.remove(ReferenceQueue.java:143)
        - locked <0x00000000d5588ec8> (a java.lang.ref.ReferenceQueue$Lock)
        at java.lang.ref.ReferenceQueue.remove(ReferenceQueue.java:164)
        at java.lang.ref.Finalizer$FinalizerThread.run(Finalizer.java:209)

"Reference Handler" #2 daemon prio=10 os_prio=2 tid=0x00000000575c3800
nid=0x1db4 in Object.wait() [0x0000000058a6f000]   
java.lang.Thread.State: WAITING (on object monitor)
        at java.lang.Object.wait(Native Method)
        - waiting on <0x00000000d5586b68> (a java.lang.ref.Reference$Lock)
        at java.lang.Object.wait(Object.java:502)
        at java.lang.ref.Reference.tryHandlePending(Reference.java:191)
        - locked <0x00000000d5586b68> (a java.lang.ref.Reference$Lock)
        at java.lang.ref.Reference$ReferenceHandler.run(Reference.java:153)

"VM Thread" os_prio=2 tid=0x00000000575bb800 nid=0x2134 runnable

"GC task thread#0 (ParallelGC)" os_prio=0 tid=0x00000000023ad800
nid=0x275c runnable

"GC task thread#1 (ParallelGC)" os_prio=0 tid=0x00000000023af000
nid=0x728 runnable

"GC task thread#2 (ParallelGC)" os_prio=0 tid=0x00000000023b0800
nid=0x1ee4 runnable

"GC task thread#3 (ParallelGC)" os_prio=0 tid=0x00000000023b2000
nid=0x1dbc runnable

"VM Periodic Task Thread" os_prio=2 tid=0x0000000058ba4000 nid=0x3c4
waiting on condition

JNI global references: 33

By way of example, we understand the specific meaning of the running thread state of Java programs.

  • Thread in their life cycle, not be fixed in a certain state, but with the implementation of the code to switch between different states
  • Java thread state changes are as follows:
    Java thread state change
    Thread creation after the call start () method starts running. When the thread executing wait () method, the thread into a wait state. The thread into a wait state need to rely on other threads notice to be able to return to the running state and the timeout wait state is equivalent to increasing the timeout limit based on the wait state, that is, will return to operational status when the timeout time is reached. When a thread calls a synchronization method, in the absence of acquired lock, the thread will enter the blocking state. After executing threads run Runnable () method will enter into the final state.

note:

  • Java will run the operating system and ready to run state called two states merged.
  • Blocked thread is blocked when entering the keyword synchronized method or block of code modified (to obtain a lock), but blocked in java. Thread state concurrent package Lock interface is a wait state because java.concurrentthe package Lock Interface for obstruction LockSupport were achieved using a class of related methods.
Published 162 original articles · won praise 219 · Views 400,000 +

Guess you like

Origin blog.csdn.net/hadues/article/details/103615042