并发编程[3]_java线程的六种状态



java线程状态

1. 操作系统进程的五种状态

网上找了一张图:
image

2. java线程的六种状态

Thread类中getState()方法可以获取线程的状态,返回值是Thread类中的enum类型,取值有NEW,RUNNABLE,BLOCKED,WAITING,TIMED_WAITING,TERMINATED六种状态。
java的线程状态将阻塞状态细分为BLOCKED,WAITING,TIMED_WAITING,将就绪和运行统称为RUNNABLE。

  • NEW:线程刚创建,还未启动时的状态
  • RUNNABLE:java中将就绪和运行两种状态中统称为RUNNABLE状态
  • BLOCKED:线程阻塞,等待获取锁
  • WAITING:线程无限制等待
  • TIMED_WAITING:线程有时限的等待
  • TERMINATED:线程执行完毕,终止状态

网上找了一张状态图:

image

例子:

public class Test1 {
    private static final Logger log = LoggerFactory.getLogger(Test1.class);

    public static void main(String[] args) throws InterruptedException {
        // 线程1 测试NEW, 未启动线程
        Thread thread1 = new Thread("thread1") {
            @Override
            public void run() {}
        };

        // 线程2 测试RUNNABLE, 启动线程且一直在运行
        Thread thread2 = new Thread("thread2") {
            @Override
            public void run() {
                while(true){

                }
            }
        };
        thread2.start();

        // 线程3 测试TIMED_WAITING, 休眠10秒,加锁
        Thread thread3 = new Thread("thread3") {
            @Override
            public void run() {
                synchronized (Test1.class){
                    try {
                        sleep(10000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        };
        thread3.start();

        // 线程4 测试WAITING,同步等待thread3
        Thread thread4 = new Thread("thread4") {
            @Override
            public void run() {
                try {
                    thread3.join();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        };
        thread4.start();

        // 线程5 测试BLOCKED,等待thread3释放锁
        Thread thread5 = new Thread("thread5") {
            @Override
            public void run() {
                synchronized (Test1.class){
                }
            }
        };
        thread5.start();

        // 线程6 测试TERMINATED,线程执行后结束
        Thread thread6 = new Thread("thread5") {
            @Override
            public void run() {}
        };
        thread6.start();

        // 主线程睡眠0.1秒,确保各线程都已启动
        Thread.sleep(100);

        log.debug("thread1: {}", thread1.getState());
        log.debug("thread2: {}", thread2.getState());
        log.debug("thread3: {}", thread3.getState());
        log.debug("thread4: {}", thread4.getState());
        log.debug("thread5: {}", thread5.getState());
        log.debug("thread6: {}", thread6.getState());
    }
}
2021-04-16 22:23:36.452  [main] - thread1: NEW
2021-04-16 22:23:36.453  [main] - thread2: RUNNABLE
2021-04-16 22:23:36.453  [main] - thread3: TIMED_WAITING
2021-04-16 22:23:36.453  [main] - thread4: WAITING
2021-04-16 22:23:36.453  [main] - thread5: BLOCKED
2021-04-16 22:23:36.453  [main] - thread6: TERMINATED
posted @ 2024-08-23 10:41  Aeons  阅读(3)  评论(0编辑  收藏  举报