• 【Java】线程状态


    1、线程状态 

    初始-NEW: Thread : 对象已经创建,但start 方法还没调用.

    终止-TERMINATED: Thread 对象还在,内核中的线程已经没了

    运行-RUNNABLE: 就绪状态(线程已经在 cpu 上执行了/线程正在排队等待上 cpu 执行)

    超时等待-TIMED WAITING: 阻塞.由于 sleep 这种固定时间的方式产生的阻塞.

    等待-WAITING: 阻塞.由于 wait 这种不固定时间的方式产生的阻塞.

    阻塞-BLOCKED:阻塞.由于锁竞争导致的阻塞.(死锁)

    2、NEW、RUNNABLE、TERMINATED

    我们通过getState()这个方法来获取线程状态

    1. public class demo {
    2. public static void main(String[] args) {
    3. Thread thread = new Thread(()->{
    4. System.out.println("线程正在执行");
    5. });
    6. System.out.println(thread.getState());
    7. thread.start();
    8. System.out.println(thread.getState());
    9. try {
    10. thread.join();
    11. } catch (InterruptedException e) {
    12. throw new RuntimeException(e);
    13. }
    14. System.out.println("main线程执行");
    15. System.out.println(thread.getState());
    16. }
    17. }

    获取状态如下 

    3、BLOCKIED-阻塞 

     BLOCKED是由于线程竞争发生死锁而导致的状态

    下面这段代码就会发生死锁

    1. public class demo {
    2. public static void main(String[] args) {
    3. Object locker1 = new Object();
    4. Object locker2 = new Object();
    5. Thread thread1 = new Thread(()->{
    6. synchronized (locker1){
    7. try {
    8. Thread.sleep(1000);
    9. } catch (InterruptedException e) {
    10. throw new RuntimeException(e);
    11. }
    12. synchronized (locker2){
    13. System.out.println("线程1进行了加锁");
    14. }
    15. }
    16. });
    17. Thread thread2 = new Thread(()->{
    18. synchronized (locker2){
    19. try {
    20. Thread.sleep(1000);
    21. } catch (InterruptedException e) {
    22. throw new RuntimeException(e);
    23. }
    24. synchronized (locker1){
    25. System.out.println("线程2进行了加锁");
    26. }
    27. }
    28. });
    29. thread1.start();
    30. thread2.start();
    31. }
    32. }

    通过jconsole查看线程状态,可知线程1、2都进入了BLOCKED状态 

     

    4、WAITING状态

    调用wait()方法,还未唤醒时,线程就处于WAITING状态

    1. public class demo {
    2. public static void main(String[] args) {
    3. Object object = new Object();
    4. Thread thread1 = new Thread(()->{
    5. synchronized (object){
    6. try {
    7. object.wait();
    8. } catch (InterruptedException e) {
    9. throw new RuntimeException(e);
    10. }
    11. }
    12. });
    13. Thread thread2 = new Thread(()->{
    14. synchronized (object){
    15. object.notify();
    16. }
    17. });
    18. thread1.start();
    19. System.out.println(thread1.getState());
    20. thread2.start();
    21. }
    22. }

    查看状态

  • 相关阅读:
    数据库中的数据
    WeetCode2滑动窗口系列
    Go数据库操作插件-xorm
    [RoarCTF 2019]Online Proxy
    【1175. 质数排列】
    Java多线程-用代码编程实现模拟机器人对话
    【Hack The Box】linux练习-- Writer
    计算机网络基础02-linux虚拟网络隔离(网桥bridge,路由,虚拟网卡veth)
    Rancher-Kubewarden-保姆级教学-含Demo测试
    C语言---二维数组&&指针
  • 原文地址:https://blog.csdn.net/m0_64921476/article/details/134467331