03-Thread State生命周期

Thread定义的线程状态

在Thread类中定义了线程状态枚举类

public enum State {
    NEW,
    RUNNABLE,
    BLOCKED,
    WAITING,
    TIMED_WAITING,
    TERMINATED;
}

1. NEW: A thread that has not yet started in this state.
2. RUNNABLE: A thread executing in the java virtual machine is in the state.
3. BLOCKED: A thread that is blocked waiting for a monitor lock is in the state.
4. WAITING: A thread that is waiting indefinitely(无限) for another thread to perform a particular action is in the state.
5. TIMED_WAITING:A thread that is waiting for another thread to perform an action for up to a specified waiting time is in the state.
6. TERMINATED: A thread that has exited is in the state.

getState方法,获取到该线程的状态,从代码中可以看到线程的状态是由JVM决定的

 public State getState() {
     // get current thread state
     return sun.misc.VM.toThreadState(threadStatus);
 }

生命周期的状态

在这里插入图片描述

一般将BLOCKED,WAITING,TIMED_WAITING都成为阻塞

代码演示示例,通过控制时间来观察线程的状态

public class ThreadStateMain {
    public static void main(String[] args)  throws  Exception{
        // 观察线程1的周期函数
        Thread one = new Thread(()-> {
            for (int i = 0; i < Integer.MAX_VALUE; i++) {
                ;
            }
            try {
                System.out.println("进入时间等待");
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                //
            }

            // 访问方法
            rvn();
        });
        // 主要用户代码块的访问
        Thread two = new Thread(()->rvn());
        // 线程2启动获取锁
        two.start();

        System.out.println("执行之前的状态:"+one.getState());
        one.start();
        System.out.println("执行中的状态:"+one.getState());
        Thread.sleep(500);
        System.out.println("线程进入时间等待:"+one.getState());
        Thread.sleep(1000);
        System.out.println("线程进入synchronized等待:"+one.getState());
        Thread.sleep(8000);
        System.out.println("执行完成: "+one.getState());
    }


    public static synchronized void rvn() {
        try {
            Thread.sleep(6000);
        }catch (InterruptedException e){
            //
        }
    }
}
/**
 执行之前的状态:NEW
 执行中的状态:RUNNABLE
 进入时间等待
 线程进入时间等待:TIMED_WAITING
 线程进入synchronized等待:BLOCKED
 执行完成: TIMED_WAITING
 */

在编写上面代码的过程中,我发现,线程的启动执行,它的时间点是不确定的,在众多线程启动并且在不确定的时间点下进入不同的状态,执行不同的代码,操作访问不同的资源,我想,这应该是多线程编程的难点所在。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值