多线程核心4:线程的六种状态

状态转换图

  • 一般把Blocked(被阻塞)、Waiting(等待)、Timed_waiting(计时等待)都称为阻塞状态
    在这里插入图片描述
  • 特殊情况:
    1. WAITING状态刚被唤醒时,通常不能立刻抢到monitor锁,这时就会从WAITING先进入BLOCKED状态,抢到锁之后再转换到RUNNABLE状态
    2. 如果在WAITING过程中,发生异常,直接跳到TERMINATION状态

六种状态具体代码

  • 线程刚创建好,还未启动,这时属于NEW状态,线程处于就绪状态或者正在运行,都是属于RUNNABLE,运行结束,进入TERMINATED

    public class NewRunnableTerminated implements Runnable {
          
          
        @Override
        public void run() {
          
          
            for (int i = 0; i < 1000; i++) {
          
          
                System.out.println(i);
            }
        }
    
        public static void main(String[] args) {
          
          
            Thread thread = new Thread(new NewRunnableTerminated());
            System.out.println(thread.getState());//NEW
            thread.start();
            System.out.println(thread.getState());//RUNNABLE
            try {
          
          
                Thread.sleep(10);
            } catch (InterruptedException e) {
          
          
                e.printStackTrace();
            }
            System.out.println(thread.getState());//RUNNABLE
    
            try {
          
          
                Thread.sleep(100);
            } catch (InterruptedException e) {
          
          
                e.printStackTrace();
            }
            System.out.println(thread.getState());//TERMINATED
        }
    }
    
  • 在thread1运行run方法时,具体操作是休眠1秒,处于BLOCKED状态,这时thread2运行run方法,但syn()方法是synchronized修饰的,thread1还没释放锁,thread2自然拿不到锁,进入计时等待TIMED_WAITING,当thread1休眠结束,马上执行wait(),thread2的状态变成等待WAITING

    public class BlockedWaitingTimedWaiting implements Runnable {
          
          
        @Override
        public void run() {
          
          
            try {
          
          
                syn();
            } catch (InterruptedException e) {
          
          
                e.printStackTrace();
            }
        }
    
        private synchronized void syn() throws InterruptedException {
          
          
            Thread.sleep(1000);
            wait();
        }
    
    
        public static void main(String[] args) throws InterruptedException {
          
          
            BlockedWaitingTimedWaiting runnable = new BlockedWaitingTimedWaiting();
            Thread thread1 = new Thread(runnable);
            thread1.start();
            Thread thread2 = new Thread(runnable);
            thread2.start();
            Thread.sleep(5);
            System.out.println(thread1.getState());//BLOCKED
            System.out.println(thread2.getState());//TIMED_WAITING
            Thread.sleep(1200);
            System.out.println(thread2.getState());//WAITING
        }
    }
    

猜你喜欢

转载自blog.csdn.net/weixin_44863537/article/details/112186800
今日推荐