java基础系列之sleep、wait、yield、interrupt

看了网上的很多资料,对着几个的说法在细节上理解还是有所不太一样,我就来谈谈我认同的一种说法。若有错或疑问,乐意被指出。

首先我们先谈谈java的线程状态

java的线程状态与底层OS的线程状态有所不同,毕竟它是属于JVM层的。
OS的线程状态图如下
这里写图片描述

JAVA的线程状态和OS的有所不同。查看jdk源代码,我们找到Thread的六种状态

 public enum State { NEW,RUNNABLE,BLOCKED,WAITING,TIMED_WAITING,TERMINATED
 }

这里写图片描述
runnable只是在JVM里已经处于运行状态,但实际上是否运行,JVM是不知道的,故JVM的rannable相当于os的就绪或运行状态。

sleep和wait的区别

  • sleep是Thread中的方法,wait是Object中的方法
  • sleep必须传时间参数,时间到后线程自动回到可运行状态或阻塞;wait之前当前线程必须获得对象的锁,且需要notify或notify唤醒,否则线程一直处于waiting状态;wait也可以定时。
  • sleep时,不会释放锁资源,它只是暂时让出OS资源给其他线程,故其他线程不能进入其锁资源区;wait后,线程进入waiting同时释放锁资源,故当它被notify或notifyAll时,可能会进入BLOCKED状态。
    对于这两个的区别我觉得网上的一段话解释得不错
    Thread.sleep(long millis) is meant for introducing pause, releasing CPU and giving another thread an opportunity to execute while wait is used for inter thread communication in Java. These methods are defined in java.lang.Object class and available to every object in Java. It is based upon object lock, if you remember every object in Java has implicit lock, also known as monitor. When a thread enter into a synchronized method it acquired the lock which is used to protect the critical reason e.g. it acquired lock on current object if it is going inside an instance synchronized method and lock object on class literal if its entering into a static synchronized method. By using wait() and notify() method two threads can communicate with each other which is key to solve many concurrency problems e.g. produce consumer problem, dining philosopher problem, reader and writer problem, and to implement several Concurrency designs.

Read more: http://www.java67.com/2012/08/what-are-difference-between-wait-and.html#ixzz4yw9tpbIz

yield

放弃,退让。
先看源代码的解释

A hint to the scheduler that the current thread is willing to yield its current use of a processor. The scheduler is free to ignore this hint.

上面说,调用yield只是,表示当前线程愿意放弃它的使用资源,但系统的调度可以选择忽略。也就是,当t1线程调用yield后,告诉系统我现在不急,你可以给我的资源给其他线程使用,但系统若觉得没有这个必要,可以忽略此意愿,让t1继续执行。

比如有小明、小王、小李向小花借车,因为先来后到的关系,小花先把车借给小明。然后小明又说我现在不急,谁若急的话可以先用。小花可能回应说你还是继续用吧,他们也不急;也可能回应说小王正好急着用车,可以先把车借给小王使用。

参考

https://segmentfault.com/a/1190000005006079
http://www.java67.com/2012/08/what-are-difference-between-wait-and.html
http://blog.jrwang.me/2016/java-thread-states/

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值