线程六种状态

线程六种状态

 

1. new状态

线程创建,还没有执行

2.runnable状态

线程正常执行

3.teminated状态

线程终止

4.block状态

阻塞状态,例如等待锁释放

5.timed_waiting状态

有时间的等待状态,线程仍在等待没有释放cpu

6.wating

等待状态

package com.study.juc;

import java.util.concurrent.TimeUnit;

//线程六种状态演示
public class ThreadStates {

    public static void main(String[] args) {
        Object lock = new Object();
        Thread t1= new Thread();
        Thread t2 = new Thread(()->{
            while (true){

            }
        });
        Thread t3 = new Thread(()->{

        });
        Thread t4 = new Thread(()->{
            try {
                synchronized (lock){
                TimeUnit.SECONDS.sleep(5);
                }
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
        });
        Thread t5 = new Thread(()->{
            try {
                synchronized (lock){
                    TimeUnit.SECONDS.sleep(5);
                }
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
        });

        Thread t6 = new Thread(()->{
            try {
                t5.join();
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
        });

        t2.start();
        t3.start();
        t4.start();
        t5.start();
        t6.start();

        try {
                TimeUnit.SECONDS.sleep(1);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }

        System.out.println(t1.getState());
        System.out.println(t2.getState());
        System.out.println(t3.getState());
        System.out.println(t4.getState());
        System.out.println(t5.getState());
        System.out.println(t6.getState());

    }
}

  输出结果

 

posted @ 2023-03-11 18:38  佳琪如梦  阅读(15)  评论(0编辑  收藏  举报