Java学习,查看线程是否存活

Java可以使用Thread类,isAlive()方法检查线程是否仍然存活。isAlive()方法返回一个布尔值,如果线程仍然在运行,则返回true;如果线程已经死亡(完成执行或未启动过),则返回false。

示例:

public class ThreadAliveExample { 
    public static void main(String[] args) throws InterruptedException {
        // 创建线程
        Thread myThread = new Thread(() -> {
            try {
                // 线程休眠
                Thread.sleep(3000);
            } catch (InterruptedException e) {
                Thread.currentThread().interrupt(); // 恢复中断状态
            }
            System.out.println("Thread has finished execution.");
        });
 
        // 启动线程
        myThread.start();
 
        // 检查线程是否存活
        System.out.println("Is thread alive? " + myThread.isAlive());
 
        // 等待一段时间
        Thread.sleep(1000);
        System.out.println("Is thread still alive after 1 second? " + myThread.isAlive());
 
        // 再等待足够长的时间,确保线程完成执行
        Thread.sleep(3000);
        System.out.println("Is thread alive after thread has finished? " + myThread.isAlive());
    }
}

运行结果:

Is thread alive? true
Is thread still alive after 1 second? true
Thread has finished execution.
Is thread alive after thread has finished? false

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值