按照惯例先吟诗一首:

《春怨 / 伊州歌》
唐代:金昌绪
打起黄莺儿,莫教枝上啼。
啼时惊妾梦,不得到辽西。

这篇主要来了解一下isAlive()方法,此方法返回当前线程是否处于“活动状态”,何为“活动状态”,线程已经启动尚未终止。

基本使用

下面用代码来说明:

MyThread类

1
2
3
4
5
6
7
8
class MyThread01 extends Thread{
@Override
public void run() {
System.out.println("Name:"+Thread.currentThread().getName());
System.out.println("state:"+Thread.currentThread().isAlive());
}
}

IsAliveTest类

1
2
3
4
5
6
7
8
public class IsAliveTest {
public static void main(String [] args){
MyThread01 thread01=new MyThread01();
System.out.println("begin:"+thread01.isAlive());
thread01.start();
System.out.println("end:"+thread01.isAlive());
}
}

结果如下:

begin:false
end:true
Name:Thread-0
state:true

将IsAliveTest类改为如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
public class IsAliveTest {
public static void main(String [] args){
MyThread01 thread01=new MyThread01();
System.out.println("begin:"+thread01.isAlive());
thread01.start();
try {
Thread.sleep(1000);
}catch (InterruptedException e){
e.printStackTrace();
}
System.out.println("end:"+thread01.isAlive());
}
}

结果如下:

begin:false
Name:Thread-0
state:true
end:false

调用Thread.sleep(1000)让主线程休眠1秒,在这1秒内Thread-0线程已经执行完毕,再调用isAlive()时返回false