线程状态

线程状态

线程的状态和进程的状态基本上一摸一样,所以这里不详细的描述

线程状态转换图

新建状态:主线程创建了子线程,但没有发送start()消息

就绪状态:分配CPU就能执行

运行状态:正在运行

阻塞状态:线程进入阻塞队列,需要被唤醒才能进入就绪状态

  • 调用sleep()方法
  • 调用join()方法
  • 发出I/O请求
  • 调用wait()方法

死亡状态:

  • 线程正常运行并退出run()方法
  • 线程运行过程发生异常未处理

深入探讨线程状态

其实,Java在实现时,阻塞状态不止一个(因为造成阻塞的原因不只一个)。

A thread state. A thread can be in one of the following states:
NEW
A thread that has not yet started is in this state.
RUNNABLE
A thread executing in the Java virtual machine is in this state.
BLOCKED
A thread that is blocked waiting for a monitor lock is in this state.
WAITING
A thread that is waiting indefinitely for another thread to perform a particular action is in this state.
TIMED_WAITING
A thread that is waiting for another thread to perform an action for up to a specified waiting time is in this state.
- TERMINATED
A thread that has exited is in this state.

第一个阻塞状态:BLOCKED

A thread that is blocked waiting for a monitor lock is in this state.

monitor lock这是后面要提到的同步监视器(也就是“锁”)。一个线程如果进入同步方法(或同步代码块)时,没有拿到锁,就会被阻塞,进入BLOCKED状态。

第二个阻塞状态:WAITING

A thread that is waiting indefinitely for another thread to perform a particular action is in this state.

一个线程不确定(indefinitely)地等待,也就是说,要阻塞多长时间是不确定地,需要等另一个线程地特定动作。

例如:一个线程调用wait()方法,这个线程被阻塞,这个线程的唤醒依赖于另一个线程调用notify()或notifyAll()方法。

第三个阻塞状态:TIMED_WAITING

明确的等待时间里,等待另一个线程的唤醒。(即使没有线程唤醒,在一段时间过后也会被唤醒)

例如:调用带参数的wait()方法,即使不被另一个线程调用notify()方法唤醒,在一段时间后也会被唤醒。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值