Java线程浅析
在回顾Java线程相关知识点时,发现互联网上很多不负责任的文章将Java线程状态与操作系统线程状态混为一谈,极为混乱,极大的误导了读者;故在此做一个详细的梳理;也望读者不要轻易相信互联网上的文章,最好亲自查证。
前言
在回顾Java线程相关知识点时,发现互联网上很多不负责任的文章将Java线程状态与操作系统线程状态混为一谈,极为混乱,极大的误导了读者;故在此做一个详细的梳理;也望读者不要轻易相信互联网上的文章,最好亲自查证。
虚拟机线程状态 vs 操作系统线程状态
Java线程状态指的是虚拟机层面暴露给开发者使用的状态,由Thread.State类定义。底层由于操作系统的千差万别,各操作系统对于线程也有不同的状态,有可能操作系统线程多个状态对应一个Java线程状态;虚拟机的存在就是统一了底层的这些差别,让开发者不必关心这些问题。
Java线程状态
自JDK1.5开始,Java在Thread;且在给定时间点上,一个线程只能处于这6种状态中的一种。
NEW
Thread state for a thread which has not yet started.
RUNNABLE
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.
BOLCKED
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
Object.wait
.
WAITING
Thread state for a waiting thread. A thread is in the waiting state due to calling one of the following methods:
Object.wait
with no timeoutThread.join
with no timeoutLockSupport.park
A thread in the waiting state is waiting for another thread to perform a particular action. For example, a thread that has called
Object.wait()
on an object is waiting for another thread to callObject.notify()
orObject.notifyAll()
on that object. A thread that has calledThread.join()
is waiting for a specified thread to terminate.
TIMED_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
with timeout
Thread.join
with timeout
LockSupport.parkNanos
LockSupport.parkUntil
TERMINATED
Thread state for a terminated thread. The thread has completed execution.
Oracle官方文档片段
|
|