Java中线程的状态

1.线程的状态

本文以java1.8为例,存在类java.lang.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 <tt>Object.wait()</tt>
         * on an object is waiting for another thread to call
         * <tt>Object.notify()</tt> or <tt>Object.notifyAll()</tt> on
         * that object. A thread that has called <tt>Thread.join()</tt>
         * 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;
    }

2.程序状态的模拟

2.1 NEW

线程没有启动之前的状态.

 @Test
    public void New() throws InterruptedException {
        Thread t1 = new Thread(()->{
            System.out.println("2:"+Thread.currentThread().getState());
        });
        System.out.println("1:"+t1.getState());
        t1.start();
        t1.join();
        System.out.println("3:"+t1.getState());
    }

输出结果:

1:NEW
2:RUNNABLE
3:TERMINATED

2.2 RUNNABLE

等待其他来自操作系统如处理器的状态。
例子如上。

2.3 BLOCKED

线程在等待锁的监控锁的状态,synchronized代码块或者方法。

 public void Bolocked() throws InterruptedException {
        final Object o = new Object();
        Thread t1 = new Thread(()->{
            synchronized (o){
                try {
                    System.out.println("t1申请到了锁....");
                    TimeUnit.SECONDS.sleep(2);
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
            }
        });
        new Thread(()->{
            synchronized (o) {
                try {
                    TimeUnit.SECONDS.sleep(5);
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
            }
        }).start();
        TimeUnit.SECONDS.sleep(1);
        t1.start();
        TimeUnit.SECONDS.sleep(1);
        System.out.println("t1:"+t1.getState());
    }

输出状态

t1:BLOCKED

2.4 WAITING

调用以下方法的时候

  • {@link Object#wait() Object.wait} with no timeout
  • {@link #join() Thread.join} with no timeout
  • {@link LockSupport#park() LockSupport.park}
 @Test
    public void Waiting() throws InterruptedException {
        final Lock lock = new ReentrantLock();
        Thread t1 = new Thread(()->{
            lock.lock();
            System.out.println("t1申请到了锁....");
            try {
                TimeUnit.SECONDS.sleep(2);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
            lock.unlock();

        });
        new Thread(()->{
           lock.lock();
            try {
                TimeUnit.SECONDS.sleep(5);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
           lock.unlock();
        }).start();
        TimeUnit.SECONDS.sleep(1);
        t1.start();
        TimeUnit.SECONDS.sleep(1);
        System.out.println("t1:"+t1.getState());
    }

输出打印结果:

t1:WAITING

2.5 TIMED_WAITING

  • {@link #sleep Thread.sleep}
  • {@link Object#wait(long) Object.wait} with timeout
  • {@link #join(long) Thread.join} with timeout
  • {@link LockSupport#parkNanos LockSupport.parkNanos}
  • {@link LockSupport#parkUntil LockSupport.parkUntil}
 @Test
    public void TIMED_WAITING() throws InterruptedException {
        Thread t1 = new Thread(() -> {
            LockSupport.park();
            try {
                TimeUnit.SECONDS.sleep(5);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
        });
        t1.start();
        SleepHelper.sleepSeconds(1);
        System.out.println("1: " + t1.getState());
        LockSupport.unpark(t1);
        TimeUnit.SECONDS.sleep(1);
        System.out.println("2: " + t1.getState());
    }

输出结果

1: WAITING
2: TIMED_WAITING
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

小刘同学要加油呀

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

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

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

打赏作者

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

抵扣说明:

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

余额充值