Java中线程(Thread对象)的六大状态

 首先,线程的状态有两种说法:

一种是将线程状态分为5种,分别是:初始化、就绪、运行、阻塞、终止,而今天分享的是另一种通过Java中Thread内部的State状态枚举类来讲解的。

  public enum State {
        /**
         * Thread state for a thread which has not yet started.
         */
        NEW,

        /**
         * Thread state for a runnable thread.  A thread in the runnable
         * state is executing in the Java virtual machine but it may
         * be waiting for other resources from the operating system
         * such as processor.
         */
        RUNNABLE,

        /**
         * Thread state for a thread blocked waiting for a monitor lock.
         * A thread in the blocked state is waiting for a monitor lock
         * to enter a synchronized block/method or
         * reenter a synchronized block/method after calling
         * {@link Object#wait() Object.wait}.
         */
        BLOCKED,

        /**
         * Thread state for a waiting thread.
         * A thread is in the waiting state due to calling one of the
         * following methods:
         * <ul>
         *   <li>{@link Object#wait() Object.wait} with no timeout</li>
         *   <li>{@link #join() Thread.join} with no timeout</li>
         *   <li>{@link LockSupport#park() LockSupport.park}</li>
         * </ul>
         *
         * <p>A thread in the waiting state is waiting for another thread to
         * perform a particular action.
         *
         * For example, a thread that has called {@code Object.wait()}
         * on an object is waiting for another thread to call
         * {@code Object.notify()} or {@code Object.notifyAll()} on
         * that object. A thread that has called {@code Thread.join()}
         * is waiting for a specified thread to terminate.
         */
        WAITING,

        /**
         * Thread state for a waiting thread with a specified waiting time.
         * A thread is in the timed waiting state due to calling one of
         * the following methods with a specified positive waiting time:
         * <ul>
         *   <li>{@link #sleep Thread.sleep}</li>
         *   <li>{@link Object#wait(long) Object.wait} with timeout</li>
         *   <li>{@link #join(long) Thread.join} with timeout</li>
         *   <li>{@link LockSupport#parkNanos LockSupport.parkNanos}</li>
         *   <li>{@link LockSupport#parkUntil LockSupport.parkUntil}</li>
         * </ul>
         */
        TIMED_WAITING,

        /**
         * Thread state for a terminated thread.
         * The thread has completed execution.
         */
        TERMINATED;
    }

以上是Java中线程状态的枚举类发现一共有六种:NEW、RUNNABLE、BLOCKED、WAITING、TIMED_WAITING、TERMINATED。

        首先是NEW状态:表示线程创建但是还没有被start运行。

其次是RUNNABLE:在线程通过start启动时,在任务执行完成前的状态为RUNNABLE。

可以看见线程执行了一个死循环,那么他的状态就一直是RUNNABLE。

接着是BLOCKED: 阻塞状态,如果拿不到锁就会出现该状态,持续阻塞等待获取锁:

package com.juc.init.线程相关;

public class ThreadState {
    public static void main(String[] args) throws InterruptedException {
        Thread t1 = new Thread(() -> {
            synchronized (ThreadState.class) {
                while (true) ; // 那锁后一直不释放
            }
        });
        t1.start();
        Thread.sleep(10); // 确保t1线程先获取锁
        Thread t2 = new Thread(() -> {
            synchronized (ThreadState.class) {
                System.out.println("hello");
            }
        });
        t2.start();
        Thread.sleep(1);
        System.out.println(t2.getState());
    }
}

 结果如下:

接着是WAITING:当线程通过join方法等待其他线程结束的过程就是WAITING:

package com.juc.init.线程相关;

public class ThreadState {
    public static void main(String[] args) throws InterruptedException {
        Thread t1 = new Thread(() -> {
                while (true) ; // 那锁后一直不释放
        });
        t1.start();
        Thread t2 = new Thread(() -> {
            try {
                t1.join(); // 确保t1执行完成,而t1是死循环,所以会一直保持WAITING状态
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
        });
        t2.start();
        Thread.sleep(10); // 确保t2线程已经执行了join方法
        System.out.println(t2.getState());
    }
}

这里就是WAITING状态,一直等着t1线程执行完毕,输出结果如下: 

接着是TIME_WAITING:也就是睡眠等待,例如:

     Thread t = new Thread(() -> {
            try {
                TimeUnit.SECONDS.sleep(10);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
        });
        t.start();
        Thread.sleep(1); // 确保t线程已经执行了sleep方法
        System.out.println(t.getState());

 输出结果如下:

最后就是 TERMINATED:表示线程已经结束:

        
        Thread t = new Thread(() -> {
            System.out.println("hello" + Thread.currentThread().getName());
        });
        t.start();
        TimeUnit.MICROSECONDS.sleep(100); // 确保t线程已经执行了start方法,并且执行输出语句
        System.out.println(t.getState());

输出结果如下: 

 

 好的本次分享的是Java中线程的六个状态,如果讲解有误请大家多多指教。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

开心与酒馆

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值