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.(对应操作系统的就绪和运行状态)
*/
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
* {@link Object#wait() Object.wait}.(监视器锁阻塞)
*/
BLOCKED, // 阻塞
/**
* 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.
*/
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:(造成延时等待的方法:)
* <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>
*/
TIMED_WAITING, // 延时等待
/**
* Thread state for a terminated thread.
* The thread has completed execution.(线程执行结束)
*/
TERMINATED; // 结束
}
监视器锁(monitor lock),又称内置锁。Java类和对象的头部会存储类和对象是否被锁定、被哪个线程锁定。类广义上也是对象,毕竟在Java世界中一切皆可为对象,所以有些资料称Java对象头存储对象是否被锁定、被哪个线程锁定。每个锁对应一个监视器,监视锁的状态。Object中的wait()、notify()、notifyAll()都是监视器对应的方法,可称为监视器方法。同步锁(synchronized)锁类,称类锁,同步锁锁对象,称对象锁。同步锁用在方法或者代码块上,即同步方法和同步代码块,基于monitor enter和monitor exit指令。
线程在操作系统层面核心状态是就绪(READY)、运行(RUNNING)、阻塞(BLOCKED)。操作系统的就绪和运行对应线程的可运行状态。操作系统的阻塞状态对应线程的阻塞、等待、延时等待。有些资料说线程在操作系统层面有5个状态,是加了创建和结束这两个状态;也有的是说就绪、运行和阻塞、等待、延时等待。