Java线程到底有几种状态

243 阅读2分钟

线程到底有几种状态?

以前对于Java线程有几种状态一直很迷,看过不同的说法,有说Java的线程有五种状态的,有说线程有六种状态的,自己也没有好好研究过,最近查看一下源码,终于知道到底哪个是对的了。

看源码:

public enum State {
        /**
         * Thread state for a thread which has not yet started.
         * 线程未开始的状态
         */
        NEW,
    
    	/**
         * 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.
         * 可运行的线程状态,此状态的线程正在JVM中运行,
         * 但也有可能在等待操作系统的其他资源,例如处理器
         */
        RUNNABLE,
    
    	/**
         * 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
         * 阻塞状态的线程在等待一个监视器锁去进入同步代码块/方法,
         * 或者调用后重新进入同步代码块/方法
         */
        BLOCKED,
    
    	/**
         * Thread state for a waiting thread.
         * A thread is in the waiting state due to calling one of the following methods:
         * Object.wait()
         * Thread.join()
         * LockSupport.park()
         * A thread in the waiting state is waiting for another thread to
         * perform a particular action.
         * 由于调用了Object.wait()、Thread.join()、LockSupport.park()其中一个方法,线程进入等待状态
         * 处于等待状态的线程,正在在等待另一个线程执行特定的操作
         */
        WAITING,
    
    	/**
         * 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:
         * Thread.sleep()
         * Object.wait()
         * LockSupport.parkNanos()
         * LockSupport.parkUntil()
         * 有指定等待时间的线程等待状态
         * 由于调用了Thread.sleep(long)、Object.wait(long)、Thread.join(long)、
         * LockSupport.parkNanos(long)、LockSupport.parkUntil(long)其中一个方法并传入了正(数)时间参数,
         * 线程处于有时间限制的等待状态
         */
        TIMED_WAITING,
    
    	/**
         * Thread state for a terminated thread.
         * The thread has completed execution.
         * 线程已经执行完成,处于终止状态
         */
        TERMINATED;
    }

源码Thread.State中写的很清楚,一共是六种状态。可以看下图:

img

线程五种状态到底是哪里传出来的?

查阅了一些资料,发现进程倒是分为三种状态或五种状态,这个五种状态和线程五种状态倒是很相像,那估计可能是弄混了?

image.png

先在这里记录一下,以后学好计算机操作系统再好好研究一下这个问题吧。