(Java) 查看线程状态

2019-04-27  本文已影响0人  jyjz2008

参考资料

  1. (豆瓣链接)Java核心技术 卷I 基础知识 第10版 英文版 的 14.3 Thread States(线程状态) 以下简称为 Java 核心技术
  2. java.lang.Thread.State 里的相关 javadoc

线程的六种状态

Java 核心技术 的 14.3 中讲述了线程状态的相关知识。线程的状态共有以下六种(在 java.lang.Thread.State 中也可以看到这六种状态的定义)

  1. NEW
    java.lang.Thread.State 里相关的 javadoc 如下

Thread state for a thread which has not yet started.

  1. RUNNABLE
    java.lang.Thread.State 里相关的 javadoc 如下

Thread state for a runnable thread. A thread in the runnable
state is executing in the Java virtual machine but it may
be waiting for other resources from the operating system
such as processor.

  1. BLOCKED
    java.lang.Thread.State 里相关的 javadoc 如下

Thread state for a thread blocked waiting for a monitor lock.
A thread in the blocked state is waiting for a monitor lock
to enter a synchronized block/method or
reenter a synchronized block/method after calling
{@link Object#wait() Object.wait}.

  1. WAITING
    java.lang.Thread.State 里相关的 javadoc 如下

Thread state for a waiting thread.
A thread is in the waiting state due to calling one of the
following methods:
<ul>
<li>{@link Object#wait() Object.wait} with no timeout</li>
<li>{@link #join() Thread.join} with no timeout</li>
<li>{@link LockSupport#park() LockSupport.park}</li>
</ul>

<p>A thread in the waiting state is waiting for another thread to
perform a particular action.

For example, a thread that has called <tt>Object.wait()</tt>
on an object is waiting for another thread to call
<tt>Object.notify()</tt> or <tt>Object.notifyAll()</tt> on
that object. A thread that has called <tt>Thread.join()</tt>
is waiting for a specified thread to terminate.

  1. TIMED_WAITING
    java.lang.Thread.State 里相关的 javadoc 如下

Thread state for a waiting thread with a specified waiting time.
A thread is in the timed waiting state due to calling one of
the following methods with a specified positive waiting time:
<ul>
<li>{@link #sleep Thread.sleep}</li>
<li>{@link Object#wait(long) Object.wait} with timeout</li>
<li>{@link #join(long) Thread.join} with timeout</li>
<li>{@link LockSupport#parkNanos LockSupport.parkNanos}</li>
<li>{@link LockSupport#parkUntil LockSupport.parkUntil}</li>
</ul>

  1. TERMINATED
    java.lang.Thread.State 里相关的 javadoc 如下

Thread state for a terminated thread.
The thread has completed execution.

如何看到六种状态的线程

由于线程共有六种状态,那么下文就分别举六个例子来进行说明。
我在写例子的时候,把代码放在 com.coder.rising 包(这些例子的代码是原创的,但是包名借用了 码农翻身
的名字)下了,在下面的六个例子中,包名部分(也就是 package com.coder.rising; 这行代码)都略去了。

  1. NEW
    程序如下
public class ShowNew {
    public static void main(String[] args) {
        System.out.println(new Thread().getState());
    }
}

运行结果如下


处于 NEW 状态的线程
  1. RUNNABLE
    程序如下
public class ShowRunnable {
    public static void main(String[] args) {
        Thread t = new Thread(new Runnable() {
            @Override
            public void run() {
                while (true) {
                    Thread.yield();
                }
            }
        });
        // 将 t 设置为后台线程, 这样在主线程结束后, t 也会被中止
        t.setDaemon(true);
        t.start();
        System.out.println(t.getState());
    }
}

运行结果如下


处于 RUNNABLE 状态的线程
  1. BLOCKED
    程序如下
public class ShowBlocked {
    public static void main(String[] args) throws Exception {
        Runnable r = new Runnable() {
            @Override
            public void run() {
                synchronized (Object.class) {
                    while (true) {
                        Thread.yield();
                    }
                }
            }
        };

        Thread t1 = new Thread(r);
        // 将 t1 设置为后台线程, 这样在主线程结束后, t1 也会被中止
        t1.setDaemon(true);
        t1.start();
        // 等待 t1 运行结束(实际上 t1 里面是个死循环, 所以超时之后, 主线程就不再等了)
        // t1.join(100) 返回时, t1 很可能已经在执行同步语句块了
        t1.join(100);

        Thread t2 = new Thread(r);
        // 将 t2 设置为后台线程, 这样在主线程结束后, t2 也会被中止
        t2.setDaemon(true);
        t2.start();

        // 等待 t2 运行结束(实际上 t2 里面是个死循环, 所以超时之后, 主线程就不再等了)
        // t2.join(100) 返回时, t2 很可能已经处于 BLOCKED 状态了
        t2.join(100);
        System.out.println(t2.getState());

    }
}

运行结果如下


处于 BLOCKED 状态的线程
  1. WAITING
    程序如下
public class ShowWaiting {
    public static void main(String[] args) throws Exception {
        Thread t = new Thread(new Runnable() {
            @Override
            public void run() {
                // 进入同步语句块时, 会持有 Object.class 上的锁
                synchronized (Object.class) {
                    try {
                        Object.class.wait();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        });

        // 将 t 设置为后台线程, 这样在主线程结束后, t 也会被中止
        t.setDaemon(true);
        t.start();
        // 等待 t 运行结束(实际上 t 很可能会在 100ms 内变为 WAITING 状态, 主线程等待 100ms 左右就继续执行后面的代码了)
        t.join(100);
        System.out.println(t.getState());
    }
}

运行结果如下


处于 WAITING 状态的线程
  1. TIMED_WAITING
    程序如下
public class ShowTimedWaiting {
    public static void main(String[] args) throws Exception {
        Thread t = new Thread(new Runnable() {
            @Override
            public void run() {
                // 进入同步语句块时, 会持有 Object.class 上的锁
                synchronized (Object.class) {
                    try {
                        Object.class.wait(10000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        });

        // 将 t 设置为后台线程, 这样在主线程结束后, t 也会被中止
        t.setDaemon(true);
        t.start();
        // 等待 t 运行结束(实际上 t 很可能会在 100ms 内变为 TIMED_WAITING 状态, 主线程等待 100ms 左右就继续执行后面的代码了)
        t.join(100);
        System.out.println(t.getState());
    }
}

运行结果如下


处于 TIMED_WAITING 状态的线程
  1. TERMINATED
    程序如下
public class ShowTerminated {
    public static void main(String[] args) throws Exception {
        Thread t = new Thread(new Runnable() {
            @Override
            public void run() {
                System.out.println("Hello world");
            }
        });

        t.start();
        t.join();
        System.out.println(t.getState());
    }
}

运行结果如下


处于 TERMINATED 状态的线程

最后附一张各个状态之间的转换关系图。图片来源是https://github.com/Snailclimb/JavaGuide/blob/master/docs/java/Multithread/JavaConcurrencyBasicsCommonInterviewQuestionsSummary.md , 而这篇文章指出,该图出自《Java 并发编程艺术》4.1.4 节

Java 线程状态间的转换关系
上一篇 下一篇

猜你喜欢

热点阅读