最近在复习java线程相关的知识,发现网络上找到的资料略显混乱,故此整理。资料大多来源于Thread.STATE源码
STATE
NEW
Thread state for a thread which has not yet started.
故名思义,就是新建的线程,但没有调用start()
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.
运行中的线程,在JVM中执行,且不在等待其他资源
BLOCKED
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()
也就是说,正在等待进入synchronized()代码块。离开此状态的办法:获得监视器锁
WAITING
Thread state for a waiting thread.
A thread is in the waiting state due to calling one of the methods:
(1).Object.wait()
(2).Thread.join()
(3).LockSupport.park()
处于这个状态的线程,离开此状态的时间取决于其他线程的动作。比如其他线程的notify(), 结束,或者unpark()。此处注意,wait()当被notify()时不会立刻往下执行,而是等待nofity()的线程离开synchronized()同步块时,才会接着执行。
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:
(1).Thread.sleep(time)
(2).Object.wait(time)
(3).Thread.join(time)
(4).LockSupport.parkNanos(time)
(5).LockSupport.parkUntil(time)
也就是有时间的WAITING状态
TERMINATED
Thread state for a terminated thread.
The thread has completed execution.
线程执行完它的start()方法后,进入的状态
阻塞状态
在我的理解下,所谓“阻塞状态”是一个粗放的概念,它对应的就是线程暂停的所有状态。根据上面的分析,BLOCKED, WAITING, TIMED_WAITING都属于阻塞状态。在一些其他资料中,发现他们这么分类:
1.等待阻塞:
wait()
2.同步阻塞:
获得监视器锁前的阻塞
3.其他阻塞:
其他阻塞状态,如:join(),sleep(),park(),或者是等待I/O
InterruptedException
1.处于上述阻塞状态的线程,都会在内部不断判断Interrupted的状态。如果发现 Interrupted == true,则抛出异常。注意:不是立刻抛出异常的,而是当获得了监视器锁之后才行。
2.线程阻塞在InterruptibleChannel类的I/O操作中
3.线程阻塞在一个Selector中时,会直接返回
LockSupport.park()也会立刻返回,但不同于以上情况,它不会将Interrupted设置为false,而是不作处理。