Java线程状态

最近在复习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,而是不作处理。

©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • rljs by sennchi Timeline of History Part One The Cognitiv...
    sennchi阅读 12,169评论 0 10
  • Java多线程入门不完全指南 序言 最近在读《把时间当作朋友》,序言就教导我“无论是谁,都是在某一刻意识到时间的珍...
    leo5592368阅读 8,831评论 2 5
  • 更多 Java 并发编程方面的文章,请参见文集《Java 并发编程》 关于 Monitor Monitor 是 J...
    专职跑龙套阅读 5,826评论 0 5
  • 所谓领导就是带领和指导。领,是起到带头作用,不论从做事做人,方式和方法。人做事的方法各有不同,可以用各自不同的方...
    山仲草堂_云岫子阅读 1,598评论 0 1
  • 婚礼日 今天是大学室友月月的婚礼。 原本需要我一早去接的可可,却在我准备出门前半小时说她起床迟了,没办法赶上高铁所...
    KKI_DD阅读 1,261评论 0 0

友情链接更多精彩内容