isAlive()方法

来源:互联网 发布:博爱社区新域名 编辑:程序博客网 时间:2024/05/18 04:52

isAlive()方法: 判断当前的线程是否处于活动状态

活动状态是指线程已经启动且尚未终止,线程处于正在运行或准备开始运行的状态,就认为线程是存活的


class MyThread extends Thread{@Override public void run(){System.out.println("run= "+this.isAlive());}}public class Run_isAlive{public static void main(String [] args){MyThread mythread = new MyThread();System.out.println("begin= "+mythread.isAlive());mythread.start();System.out.println("end= "+mythread.isAlive());}}

运行结果:  begin=f alse

                   run= true

                   end= true


针对代码:

System.out.println("end= "+mythread.isAlive());
输出结果是true,但此值是不确定的,结果为true只是因为线程还未执行完毕,如果代码更改如下:


public class Run_isAlive{public static void main(String [] args){MyThread mythread = new MyThread();System.out.println("begin= "+mythread.isAlive());mythread.start();try{           Thread.sleep(1000);}catch(InterruptedException e){e.printStackTrace();}System.out.println("end= "+mythread.isAlive());}}

运行结果: 

                   begin=f alse

                   run= true

                   end= false

结果为false,是因为mythread对象已经在1秒内执行完毕。







原创粉丝点击