JAVA 线程状态中可能存在的一些误区

空无 2021-01-21 10:20:52
java 线程 存在 状态 可能


BLOCKED和WAITING的区别

BLOCKED和WAITING两种状态从结果上来看,都是线程暂停,不会占用CPU资源,不过还是有一些区别的

BLOCKED

等待Monitor锁的阻塞线程的线程状态,处于阻塞状态的线程正在等待Monitor锁进入synchronized Block或者Method,或者在调用Object.wait后重新进入同步块/方法。简单的说,就是线程等待synchronized形式的锁时的状态

下面这段代码中,t1在等待t0的锁释放(synchronized代码块执行完成),那么此时t1的状态就是BLOCKED

Object lock = new Object();
Thread t0 = new Thread(new Runnable() {
@Override
public void run() {
synchronized (lock){
System.out.println("t0 acquire lock success");
try {
Thread.sleep(10000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
});
t0.start();
Thread.sleep(100);
Thread t1 = new Thread(new Runnable() {
@Override
public void run() {
synchronized (lock){
System.out.println("t1 acquire lock success");
}
}
});
t1.start();
Thread.sleep(100);
System.out.println("t0 state: "+t0.getState());
System.out.println("t1 state: "+t1.getState());
System.out.println("done.");
//output
t0 acquire lock success
t0 state: TIMED_WAITING
t1 state: BLOCKED
done.
t1 acquire lock success

WAITING

等待中的线程状态,下面几个方法的调用会导致线程进入WAITING状态:

  • Object.wait()
  • Thread.join()
  • LockSupport.park()

WAITING状态中的线程在等待其他线程执行某些操作,比如在某个对象上调用Object.wait()的线程正在等待另一个线程在该对象上调用Object.notify()或Object.notifyAll()。为Thread.join()的线程正在等待指定的线程停止。

下面这段代码中,t0在通过synchronized获取了lock对象的锁之后,进行了wait操作,导致t0进入WAITING状态:

Object lock = new Object();
Thread t0 = new Thread(new Runnable() {
@Override
public void run() {
synchronized (lock){
System.out.println("t0 acquire lock success");
try {
lock.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
});
t0.start();
Thread.sleep(100);
System.out.println("t0 state: "+t0.getState());
System.out.println("done.");
//output
t0 acquire lock success
t0 state: WAITING
done.

区别

JAVA中除了synchronized Block/Method的锁,还提供了JUC下的锁实现,juc.lock下的锁功能更强大。比如支持中断,支持重入/非重入,公平/非公平等;但是juc下的锁和synchronized的实现可是不太一样的

比如下面这段代码,同样是等待锁,可是和synchronized等待锁的状态还不一样:

ReentrantLock reentrantLock = new ReentrantLock();
Thread t0 = new Thread(new Runnable() {
@Override
public void run() {
reentrantLock.lock();
System.out.println("t0 acquire lock success");
try {
Thread.sleep(10000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
});
t0.start();
Thread.sleep(100);
Thread t1 = new Thread(new Runnable() {
@Override
public void run() {
reentrantLock.lock();
System.out.println("t1 acquire lock success");
}
});
t1.start();
Thread.sleep(100);
System.out.println("t0 state: "+t0.getState());
System.out.println("t1 state: "+t1.getState());
System.out.println("done.");
//output
t0 acquire lock success
t0 state: TIMED_WAITING
t1 state: WAITING
done.

同样是加锁,在JUC的锁实现下线程状态不太一样,所以在观察线程状态时,不止是BLOCKED的状态才是等待锁,WAITING/TIMEWAITING的状态仍然可能是等待锁的状态

不过JUC下的锁实现,让线程暂停/等待的核心方法还是LockSupport.park,jstack对于PARKING形式的WAITING会有标注,所以在线程stack时还是能一眼看出来的:

//这里显示了等待类型
"Thread-0" #11 prio=5 os_prio=31 tid=0x00007f9308110000 nid=0x5c03 waiting on condition [0x0000700007fc3000]
java.lang.Thread.State: WAITING (parking)//这里虽然是WAITING,但还是标注了是parking类型的
at sun.misc.Unsafe.park(Native Method)

而synchronized形式的锁在jstack下的输出会有所区别:

//这里显示了等待类型为monitor
"Thread-1" #12 prio=5 os_prio=31 tid=0x00007f833d919800 nid=0x5a03 waiting for monitor entry [0x00007000035af000]
java.lang.Thread.State: BLOCKED (on object monitor)//这里是BLOCKED状态,同时显示了monitor的归属

所以在观察线程状态时,需要注意Object.wait()这种WAITING和juc下锁导致的WAITING的区别

RUNNABLE真的是RUNNABLE吗?

下面是一段jstack输出的例子,该线程现在正在执行socketRead0方法(Native),并且是RUNNABLE状态

"RMI TCP Connection(2)-192.xxx.xx.xx" daemon prio=6 tid=0x000000000a3e8800 nid=0x158e50 runnable [0x000000000adbe000]
java.lang.Thread.State: RUNNABLE
at java.net.SocketInputStream.socketRead0(Native Method)
at java.net.SocketInputStream.read(Unknown Source)
at java.net.SocketInputStream.read(Unknown Source)
at java.io.BufferedInputStream.fill(Unknown Source)
at java.io.BufferedInputStream.read(Unknown Source)
- locked (0x00000007ad784010) (a java.io.BufferedInputStream)
at java.io.FilterInputStream.read(Unknown Source)
at sun.rmi.transport.tcp.TCPTransport.handleMessages(Unknown Source)
at sun.rmi.transport.tcp.TCPTransport$ConnectionHandler.run0(Unknown Source)
at sun.rmi.transport.tcp.TCPTransport$ConnectionHandler.run(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
at java.lang.Thread.run(Unknown Source)

但其实这里的RUNNABLE只是JAVA层面的线程状态,在操作系统或进程角度来看,该线程还是WAITING的状态;SocketInputStream是一个BIO的实现,当没有收到数据(或者说没有准备好可读的数据)时会发生阻塞,可这个阻塞在JAVA线程状态里是RUNNABLE的状态,不过他并不会占用用户态的CPU时间片,内核在接受到数据后会结束这个阻塞

参考

版权声明
本文为[空无]所创,转载请带上原文链接,感谢
https://segmentfault.com/a/1190000039044989

  1. 【计算机网络 12(1),尚学堂马士兵Java视频教程
  2. 【程序猿历程,史上最全的Java面试题集锦在这里
  3. 【程序猿历程(1),Javaweb视频教程百度云
  4. Notes on MySQL 45 lectures (1-7)
  5. [computer network 12 (1), Shang Xuetang Ma soldier java video tutorial
  6. The most complete collection of Java interview questions in history is here
  7. [process of program ape (1), JavaWeb video tutorial, baidu cloud
  8. Notes on MySQL 45 lectures (1-7)
  9. 精进 Spring Boot 03:Spring Boot 的配置文件和配置管理,以及用三种方式读取配置文件
  10. Refined spring boot 03: spring boot configuration files and configuration management, and reading configuration files in three ways
  11. 精进 Spring Boot 03:Spring Boot 的配置文件和配置管理,以及用三种方式读取配置文件
  12. Refined spring boot 03: spring boot configuration files and configuration management, and reading configuration files in three ways
  13. 【递归,Java传智播客笔记
  14. [recursion, Java intelligence podcast notes
  15. [adhere to painting for 386 days] the beginning of spring of 24 solar terms
  16. K8S系列第八篇(Service、EndPoints以及高可用kubeadm部署)
  17. K8s Series Part 8 (service, endpoints and high availability kubeadm deployment)
  18. 【重识 HTML (3),350道Java面试真题分享
  19. 【重识 HTML (2),Java并发编程必会的多线程你竟然还不会
  20. 【重识 HTML (1),二本Java小菜鸟4面字节跳动被秒成渣渣
  21. [re recognize HTML (3) and share 350 real Java interview questions
  22. [re recognize HTML (2). Multithreading is a must for Java Concurrent Programming. How dare you not
  23. [re recognize HTML (1), two Java rookies' 4-sided bytes beat and become slag in seconds
  24. 造轮子系列之RPC 1:如何从零开始开发RPC框架
  25. RPC 1: how to develop RPC framework from scratch
  26. 造轮子系列之RPC 1:如何从零开始开发RPC框架
  27. RPC 1: how to develop RPC framework from scratch
  28. 一次性捋清楚吧,对乱糟糟的,Spring事务扩展机制
  29. 一文彻底弄懂如何选择抽象类还是接口,连续四年百度Java岗必问面试题
  30. Redis常用命令
  31. 一双拖鞋引发的血案,狂神说Java系列笔记
  32. 一、mysql基础安装
  33. 一位程序员的独白:尽管我一生坎坷,Java框架面试基础
  34. Clear it all at once. For the messy, spring transaction extension mechanism
  35. A thorough understanding of how to choose abstract classes or interfaces, baidu Java post must ask interview questions for four consecutive years
  36. Redis common commands
  37. A pair of slippers triggered the murder, crazy God said java series notes
  38. 1、 MySQL basic installation
  39. Monologue of a programmer: despite my ups and downs in my life, Java framework is the foundation of interview
  40. 【大厂面试】三面三问Spring循环依赖,请一定要把这篇看完(建议收藏)
  41. 一线互联网企业中,springboot入门项目
  42. 一篇文带你入门SSM框架Spring开发,帮你快速拿Offer
  43. 【面试资料】Java全集、微服务、大数据、数据结构与算法、机器学习知识最全总结,283页pdf
  44. 【leetcode刷题】24.数组中重复的数字——Java版
  45. 【leetcode刷题】23.对称二叉树——Java版
  46. 【leetcode刷题】22.二叉树的中序遍历——Java版
  47. 【leetcode刷题】21.三数之和——Java版
  48. 【leetcode刷题】20.最长回文子串——Java版
  49. 【leetcode刷题】19.回文链表——Java版
  50. 【leetcode刷题】18.反转链表——Java版
  51. 【leetcode刷题】17.相交链表——Java&python版
  52. 【leetcode刷题】16.环形链表——Java版
  53. 【leetcode刷题】15.汉明距离——Java版
  54. 【leetcode刷题】14.找到所有数组中消失的数字——Java版
  55. 【leetcode刷题】13.比特位计数——Java版
  56. oracle控制用户权限命令
  57. 三年Java开发,继阿里,鲁班二期Java架构师
  58. Oracle必须要启动的服务
  59. 万字长文!深入剖析HashMap,Java基础笔试题大全带答案
  60. 一问Kafka就心慌?我却凭着这份,图灵学院vip课程百度云