Java线程的状态

线程的状态

  • 在Java源码中给线程定义了6种状态
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: *
    *
  • {@link Object#wait() Object.wait} with no timeout
  • *
  • {@link #join() Thread.join} with no timeout
  • *
  • {@link LockSupport#park() LockSupport.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 call * Object.notify() or Object.notifyAll() on * that object. A thread that has called Thread.join() * 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: *
    *
  • {@link #sleep Thread.sleep}
  • *
  • {@link Object#wait(long) Object.wait} with timeout
  • *
  • {@link #join(long) Thread.join} with timeout
  • *
  • {@link LockSupport#parkNanos LockSupport.parkNanos}
  • *
  • {@link LockSupport#parkUntil LockSupport.parkUntil}
  • *
*/ TIMED_WAITING,/** * Thread state for a terminated thread. * The thread has completed execution. */ TERMINATED; }

  • NEW :线程刚被创建,还没有调用start()之前就处于该状态
  • RUNNABLE :在调用start()之后,线程就处于运行状态。Java线程中将就绪(ready)和运行中(running)两种状态笼统的称为“运行,我们知道,操作系统对线程的调度多是抢占式的。也就是说调用了start()之后不一定马上可以执行,而是被放置在可运行线程池中,说明该线程是处于就绪状态,可以被运行了,这个时候的线程在等待线程调度,直到等到cpu时间分片到了才会真正的执行。注释中也说明了该问题:but it may be waiting for other resources from the operating system such as processor.
  • BLOCKED :处于BLOCKED表示该线程阻塞于锁。当线程在等待一个监视器的锁去进入一个synchronized block/method (同步[块|方法])或者在调用了Object#wait()后被notify后重新进入synchronized block/method依旧需要等待该锁,线程就会处于阻塞状态
  • WAITING :处于WAITING表明该线程正在等待另一个线程执行特定的操作。当调用了Object#wait()Thread#join()LockSupport#park()中的某一个方法(需注意是with no timeout的)之后。线程就会处于等待状态。等待的是其它线程的通知或者终止状态
  • TIMED_WAITING : 具有指定等待时间的等待线程的线程状态。与WAITING不同的是该状态在指定等待时间之后会自行返回。当调用了Thread.sleepObject#wait(long)Thread.join(long)LockSupport#parkNanosLockSupport#parkUntil 方法之一后。线程就处于等待状态,在指定的时间没有被唤醒或者等待线程没有结束,会被系统自动唤醒,正常退出
  • TERMINATED :终止状态,表明线程已经执行完了run方法。该状态只是代表着线程已经执行完了run方法,实际上操作系统里线程可能被注销了,也可能复用给其它线程任务请求。
状态验证
  • 首先来看线程没有任何阻塞、等待处理的情况
class ThreadTest { @Test fun test() { val thread = MyThread() println("thread state before start:${thread.state}") thread.start() Thread.sleep(200)//睡200ms等待run执行完成 println("thread state after run :${thread.state}") }class MyThread :Thread(){ override fun run() { super.run() println("thread state on run:$state") } } }

  • 运行结果如下
Java线程的状态
文章图片
线程状态-NEW_RUNNABLE_TERMINATED.png
  • 由于抢占锁而处于阻塞状态
class ThreadTest {@Test fun test() { val lock = Object() val thread1 = MyThread("thread 1",lock) thread1.start() Thread.sleep(200) //等待200ms 让thread1被调度执行val thread2 = MyThread("thread 2",lock) thread2.start() Thread.sleep(200) //等待200ms 让thread2被调度执行 ,此时thread1已经持有锁了println("thread2 state :${thread2.state}") }class MyThread constructor(name: String,var lock:Object) : Thread(name) { override fun run() { super.run() println("$name try to hole the lock") synchronized(lock) { println("$namehole the lock now") sleep(1000 * 1000) } } } }

  • 运行结果如下
Java线程的状态
文章图片
线程状态_BLOCKED.png
  • 由于等待其它线程的特定操作而处于等待状态,直到被通知
class ThreadTest {@Test fun test() { val lock = Object() val thread1 = MyThread("thread 1",lock) thread1.start() Thread.sleep(200) //等待200ms 让thread1被调度执行,进入等待状态println("thread1 state :${thread1.state}") }class MyThread constructor(name: String,var lock:Object) : Thread(name) { override fun run() { super.run() synchronized(lock){ //在调用lock之前需要使用synchronized语义绑定住被wait/notify的对象 println("$name state:$state") lock.wait() println("$name state:$state") } } } }

  • 运行结果如下
Java线程的状态
文章图片
线程状态_WAITING.png
class ThreadTest {@Test fun test() { val lock = Object() val thread1 = MyThread("thread 1",lock) thread1.start() Thread.sleep(200) //等待200ms 让thread1被调度执行,进入等待状态println("thread1 state :${thread1.state}")synchronized(lock) { lock.notifyAll() //通知 }Thread.sleep(200) println("thread1 state after notify:${thread1.state}") }class MyThread constructor(name: String,var lock:Object) : Thread(name) { override fun run() { super.run() synchronized(lock){ //在调用wait()之前需要使用synchronized语义绑定住被wait/notify的对象(获取到锁) println("$name state:$state") lock.wait() println("$name state:$state") } } } }

  • 运行结果如下
Java线程的状态
文章图片
线程状态_等待唤醒.png
  • 具有指定等待时间的等待线程的线程状态
class ThreadTest {@Test fun test() { val thread1 = MyThread("thread 1") Object().wait(1000) thread1.start() Thread.sleep(200) //等待200ms 让thread1被调度执行,进入等待状态 println("thread1 state :${thread1.state}") Thread.sleep(1000) //等待1000ms 让线程run执行完成 println("thread1 state :${thread1.state}") }class MyThread constructor(name: String) : Thread(name) { override fun run() { super.run() println("$name state:$state") sleep(1000) println("$name state:$state") } } }

  • 运行结果如下
Java线程的状态
文章图片
线程状态_TIMED_WAITING .png
  • Object#wait(long)进入等待状态
class ThreadTest {@Test fun test() { val lock = Object() val thread1 = MyThread("thread 1",lock,false) thread1.start() Thread.sleep(200) //等待200ms 让thread1被调度执行,进入等待状态 println("thread1 state :${thread1.state}")Thread.sleep(3000) //等待3000ms 让线程thread1 run能够继续执行 thread1.condition = true //让条件满足Thread.sleep(2000) ///等待2000ms 确保让线程thread1 run执行 println("thread1 state :${thread1.state}") }class MyThread constructor(name: String,var lock:Object,var condition:Boolean) : Thread(name) {override fun run() { super.run() synchronized(lock){ while (!condition){ println("$name state:$state") lock.wait(1000) println("$name continue run at ${System.currentTimeMillis()}") }println("do sth when meet the conditions") println("$name state:$state") }} } }

  • 运行结果如下
Java线程的状态
文章图片
TIMED_WAITING.png
  • 需要注意的是实际上每次thread 1由于while循环每次超时唤醒之后又会重新进入TIMED_WAITING,然后才 continue run 直到条件符合退出循环
  • TIMED_WAITING状态之后是有一个最多等待时间的,在超时之后线程会自动被唤醒,无需手动notify,当然也可以提前通过notify唤醒线程。从上面的运行结果相信读者可以很好的体会出WAITINGTIMED_WAITING的区别
状态图
  • 通过源码注释及上面的分析我们可以画一个状态图
Java线程的状态
文章图片
线程状态图.png Object.wait、Thread.sleep、LockSupport.park、等方法的异同 在前面的状态图中列举了非常多方法,那么它们的的区别是什么呢?怎么使用它们才能保证线程的状态是符合我们的预期的(程序的功能符合预期)
  • Object.wait
    1. 调用之前需要先获取锁,也就是被synchronized原语绑定
    2. 调用之后线程会释放占有的锁 ,从测试用例的调用过程就可以看出来。调用obj.wait的时候和其它多线程调用obj.notifyAll的时候都需要先获取锁,如果调用obj.wait的时候没有释放锁,那么别的线程就无法获取该对象锁来notify
    3. 不传时间会一直阻塞,直到另一个线程调用notify()/notifyAll()将其唤醒,传入时间,如果其它线程一直没有调用notify()/notifyAll(), 到了时间会自动唤醒。被唤醒之后如果立即获得锁,会继续执行,如果没有获得锁,会进入同步队列等待获取锁,也就是不一定会执行后面的逻辑
    4. 可响应interrupt()中断,并且抛出InterruptedException
    5. notify()/notifyAll()必须在wait()之后调用,否则会抛出IllegalMonitorStateException异常,并且无法指定唤醒哪个线程
  • Thread.join
    1. 从jdk源码中可以看到该方法的实现的原理实际上利用了 synchronized(lock) {while (isAlive()) { lock.wait(0); }}实现的,也就是说调用该线程的join方法的时候实际上需要先获取该线程对象的锁,否则也是会被阻塞的
    2. 线程A调用线程B#join方法之后,线程A一直阻塞直到B为TERMINATED状态即被唤醒,所以一般可用来实现线程的同步运行,即按顺序执行
    3. 可响应interrupt()中断,并且抛出InterruptedException
  • Thread.sleep
    1. 不会释放当前线程占有的锁资源
    2. 在指定时间之后自动唤醒
    3. 可响应interrupt()中断,并且抛出InterruptedException
  • LockSupport.park
    1. 调用之前无需获取锁
    2. 调用之后不会释放当前线程占有的锁资源
    3. 可响应interrupt()中断,不会抛出InterruptedException
    4. 可调用LockSupport.unpart(Thread)指定唤醒某一线程,并且一定会执行后面的逻辑
    5. LockSupport.unpart(Thread)可在LockSupport.park 之前调用,unpart先调用之后,调用park不会阻塞,会直接运行
    6. 多次调用LockSupport.unpart(Thread),只能获得一次许可,无法叠加,只要调用LockSupport.park 就会被消费,随后调用LockSupport.park 会被阻塞
关于锁的释放的补充 【Java线程的状态】前面说到Object.wait是会释放锁的,那么是释放Object的锁还是释放线程持有的所有锁呢?关于Object.wait释放锁,我想你能搜到的99.9%的文章都是只说了这么一句——Object.wait是会释放锁。先来看一个例子
class ThreadTest {@Test fun test() { val lock = Object() val lock2 = Object() val thread = Thread1("thread 1",lock,lock2) thread.start() Thread.sleep(200)synchronized(lock2){//先获取lock2看下会不会被释放 synchronized(lock){ lock.notifyAll() } }Thread.sleep(1000) //等待thread 1执行完成println("thread1 state :${thread.state}") }classThread1constructor(name: String,var lock:Object,var lock2:Object) : Thread(name){ override fun run() { super.run() synchronized(lock){ //持有lock2锁 synchronized(lock2){ //持有lock2锁 lock.wait()println("$name 被唤醒") } }} }}

  • 猜猜上面的运行结果是什么? 会被唤醒吗?
Java线程的状态
文章图片
main dump信息.png Java线程的状态
文章图片
thread 1 Dump信息.png
  • 关于Object.wait会释放synchronized锁住的Object锁毋庸置疑,如果不能释放的话也就没有notify一说了。实际上的运行结果是main thread 和 thread 1都阻塞了。仔细看一下线程的dump信息,可以看到thread 1处于WAITING状态,并且它 - locked <0x000000076be35ff8>,而main thread被阻塞了,处于BLOCKED,它- waiting to lock <0x000000076be35ff8>。这不正是前面分析过的,由于进入synchronized(lock2)获取不到锁而处于BLOCKED状态。所以说,Object.wait实际上是调用哪个哪个对象的wait方法,就释放该对应对象的锁。
  • 那么既然Thread.join方法实际上是依赖于Object.wait实现的,释放哪个监视器锁也就清楚了

    推荐阅读