某大厂一面:Java 线程的生命周期

Java 中线程的生命周期通常包括以下几个状态:

  1. 新建状态 (New):线程被创建,但尚未启动。
  2. 就绪状态 (Runnable):线程已经启动,但等待操作系统调度执行。
  3. 运行状态 (Running):线程正在执行。
  4. 阻塞状态 (Blocked):线程由于某些原因(如等待锁)被阻塞,无法继续执行。
  5. 等待状态 (Waiting):线程等待某些条件发生才能继续执行,通常是通过 wait()join() 等方法。
  6. 超时等待状态 (Timed Waiting):线程在指定时间内等待某个条件,超时后会自动返回。
  7. 终止状态 (Terminated):线程执行完毕或被中止。

下面是一个简单的 Java 代码示例,展示了线程生命周期的各个阶段:

class ThreadLifecycleDemo extends Thread {

    @Override
    public void run() {
        try {
            System.out.println(Thread.currentThread().getName() + " is in Running state.");
            // Simulate some work
            Thread.sleep(2000); // This will cause the thread to go into Timed Waiting state
            System.out.println(Thread.currentThread().getName() + " finished sleeping.");
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) throws InterruptedException {
        // Step 1: New state
        ThreadLifecycleDemo thread = new ThreadLifecycleDemo();
        System.out.println("Thread state after creation: " + thread.getState());

        // Step 2: Start thread - Runnable state
        thread.start();
        System.out.println("Thread state after start: " + thread.getState());

        // Wait for the thread to sleep and then finish
        Thread.sleep(500); // This allows the thread to enter a running state before checking again

        // Step 3: Checking state while thread is running
        System.out.println("Thread state while running (before sleep): " + thread.getState());

        // Wait until the thread finishes its work
        thread.join(); // This makes the main thread wait for 'thread' to complete

        // Step 4: After thread finishes - Terminated state
        System.out.println("Thread state after completion: " + thread.getState());
    }
}

代码解析:

  1. 新建状态 (New):在调用 new ThreadLifecycleDemo() 时,线程对象还没有启动,此时线程处于新建状态。

  2. 就绪状态 (Runnable):调用 thread.start() 后,线程进入就绪状态,等待操作系统调度执行。

  3. 运行状态 (Running):线程开始执行 run() 方法中的代码,在 Thread.sleep(2000) 时,线程进入了“超时等待”状态。

  4. 超时等待状态 (Timed Waiting)Thread.sleep(2000) 会使线程进入等待状态,直到指定时间过去。

  5. 终止状态 (Terminated):当 run() 方法执行完毕,线程进入终止状态。

线程状态的输出:

  • 在创建线程时,输出:Thread state after creation: NEW
  • 在启动线程后,输出:Thread state after start: RUNNABLE
  • 当线程运行并在 sleep() 时,输出:Thread state while running (before sleep): TIMED_WAITING
  • 线程执行完毕后,输出:Thread state after completion: TERMINATED
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

冰糖心书房

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

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

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

打赏作者

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

抵扣说明:

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

余额充值