线程的生命周期

线程的生命周期

1.新建 New

我们线程对象刚创建好,还没执行start方法。

2.就绪 Runnable

调用start方法后就进入就绪状态,登台JVM线程调度器分配CPU的时间片来执行线程的run方法。

3.运行 Running

当我们线程获得了CPU的时间片就开始真正的执行run方法。

4.堵塞 Blocked

线程在等待获取一个同步锁的时候就会进入堵塞状态,比如当一个线程

public class ThreadBlockingExample {
    
    private static final Object lock = new Object();
    
    public static void main(String[] args) {
        Thread t1 = new Thread(() -> {
            synchronized (lock) {
                try {
                    System.out.println("Thread 1: Holding lock...");
                    Thread.sleep(3000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                System.out.println("Thread 1: Released lock.");
            }
        });

        Thread t2 = new Thread(() -> {
            System.out.println("Thread 2: Waiting for lock...");
            synchronized (lock) {
                System.out.println("Thread 2: Acquired lock.");
            }
        });

        t1.start();
        try {
            Thread.sleep(100); // Ensure t1 acquires the lock first
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        t2.start();

        try {
            Thread.sleep(100); // Allow t2 to attempt acquiring the lock
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        
        System.out.println("State of Thread 2: " + t2.getState()); // Should print BLOCKED

        try {
            t1.join();
            t2.join();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        
        System.out.println("State of Thread 2 after join: " + t2.getState()); // Should print TERMINATED
    }
}

5. 等待 Waiting

等待状态就是线程需要被其他线程唤醒。

当执行Object.wait(); Thread.join(); LockSupport.park()就会进入Waiting状态.

LockSupport

LockSupport.park() 用于阻塞当前线程,直到 LockSupport.unpark(Thread thread) 唤醒它。

LockSupport他不需要特定的锁就可以堵塞和唤醒线程。随时可以用unpark进行唤醒可以更好的精准控制。

LockSupport案例

import java.util.concurrent.locks.LockSupport;

public class LockSupportExample {

    public static void main(String[] args) {
        Thread thread = new Thread(() -> {
            System.out.println("Thread is going to park.");
            LockSupport.park();
            System.out.println("Thread is unparked and resumed.");
        });

        thread.start();

        try {
            Thread.sleep(2000); // 主线程睡眠2秒确保子线程进入park状态
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        System.out.println("Main thread is going to unpark the thread.");
        LockSupport.unpark(thread); // 唤醒子线程
    }
}

Object.wait

public class WaitNotifyExample {

    private static final Object lock = new Object();

    public static void main(String[] args) {
        Thread thread = new Thread(() -> {
            synchronized (lock) {
                try {
                    System.out.println("Thread is going to wait.");
                    lock.wait();
                    System.out.println("Thread is notified and resumed.");
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        });

        thread.start();

        try {
            Thread.sleep(2000); // 主线程睡眠2秒确保子线程进入wait状态
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        synchronized (lock) {
            System.out.println("Main thread is going to notify the thread.");
            lock.notify(); // 唤醒子线程
        }
    }
}

Thead.join()

当前线程等这个线程执行完。join会自动唤醒。

public class ThreadJoinExample {
    public static void main(String[] args) {
        Thread t1 = new Thread(() -> {
            try {
                Thread.sleep(2000); // 模拟工作
                System.out.println("Thread 1 finished.");
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        });

        Thread t2 = new Thread(() -> {
            try {
                Thread.sleep(1000); // 模拟工作
                System.out.println("Thread 2 finished.");
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        });

        t1.start();
        t2.start();

        try {
            t1.join(); // 主线程等待t1执行完毕
            t2.join(); // 主线程等待t2执行完毕
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        System.out.println("All threads have finished.");
    }
}

6.计时等待

经过N秒会自动唤醒

Thread.sleep(long millis);

Object.wait(long timeout);

Thread.join(long millis);

LockSupport.parkNanos(long nanos); 可以被unpark唤醒

LockSupport.parkUntil(long deadline); 到一个决定的时间唤醒

7.死亡

run执行完了,或者异常退出。

  • 5
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

哇塞大嘴好帅(DaZuiZui)

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

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

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

打赏作者

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

抵扣说明:

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

余额充值