河北银丹互联网科技有限公司class Mythread extends Thread{河北银丹互联网科技有限公司
@Override
public void run() {
System.out.println("run =="+this.isAlive());
}
}
public class Test01 {
public static void main(String[] args) {
Mythread thread=new Mythread();
System.out.println("begin =="+thread.isAlive());//①
thread.start();//②
System.out.println("end =="+thread.isAlive());//③
}
}
结果:
begin ==false
end ==true
run ==true
方法isAlive()的作用是测试线程是否处于活动状态。那么什么情况下是活动状态呢?活动状态就是线程已经启动且尚未停止。线程处于正在运行或准备开始运行的状态,就认为线程是存活的
①处代码的结果为false,因为此时线程还未启动;
②处代码调用了run()方法输出结果为run ==true,此时线程处于活动状态;
③处代码的结果为true,有的同学看到这个输出可能会不理解,不是说线程处于活动状态isAlive()方法的结果才是true,现在程序都已经运行结束了为什么还是true?这里的输出结果是不确定的,我们再来看下面一段代码
我们将例1中的代码稍做修改,代码如下:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
public class Test01 {
public static void main(String[] args) throws InterruptedException {
Mythread thread=new Mythread();
System.out.println("begin =="+thread.isAlive());//①
thread.start();//②
Thread.sleep(1000);//这里加了一行代码,让当前线程沉睡1秒
System.out.println("end =="+thread.isAlive());//③
}
}
结果:
begin ==false
run ==true
end ==false