虽然Thread类实现了Runnable接口,但是操作线程的主要方法并不在Runnable接口中,多线程操作,主要是通过Thread类中的方法实现。
线程的创建是用Thread类的构造方法,因此线程操作的主要方法是Thread类中的方法。
本文介绍如何判断线程是否启动。
通过Thread类中的start方法通知CPU这个线程已经准备好了,等待分配CPU资源后运行线程。
在Java中可以使用isAlive方法来判断线程是否已经启动。
示例1:判断线程是否启动
// 测试类
public class TaskAliveTest {
public static void main(String[] args) {
Task task = new Task();
Thread thread = new Thread(task, "thread线程");
System.out.println("调用start方法前,thread.isAlive=" + thread.isAlive());
thread.start();
System.out.println("调用start方法后,thread.isAlive=" + thread.isAlive());
for (int i = 0; i < 3; i++) {
System.out
.println(Thread.currentThread().getName() + "线程运行,i=" + i);
}
System.out.println("main方法执行完毕时,thread.isAlive=" + thread.isAlive());
}
}
程序运行结果:
调用start方法前,thread.isAlive=false
调用start方法后,thread.isAlive=true
main线程运行,i=0
main线程运行,i=1
main线程运行,i=2
main方法执行完毕时,thread.isAlive=true
线程运行,i=1
线程运行,i=2
线程运行,i=3
从上面的程序看以看出,在调用thread线程的start方法前,thread线程没有存活,调用start方法后,thread线程启动了,随后CPU资源被main线程抢占,开始执行main线程的代码,main方法执行完毕时,thread线程依然存活着,最后thread线程获得了CPU的资源,开始执行自己的run方法的代码,输出1-3的数字。
示例2:main线程加入休眠,判断线程是否存活
// 测试类
public class TaskAliveTest {
public static void main(String[] args) {
Task task = new Task();
Thread thread = new Thread(task, "thread线程");
System.out.println("调用start方法前,thread.isAlive=" + thread.isAlive());
thread.start();
System.out.println("调用start方法后,thread.isAlive=" + thread.isAlive());
try {
Thread.sleep(10); // 为了观察线程代码执行后,线程是否存活,让主线程休眠
} catch (InterruptedException e) {
e.printStackTrace();
}
for (int i = 0; i < 3; i++) {
System.out
.println(Thread.currentThread().getName() + "线程运行,i=" + i);
}
System.out.println("main方法执行完毕时,thread.isAlive=" + thread.isAlive());
}
}
程序运行结果:
调用start方法前,thread.isAlive=false
调用start方法后,thread.isAlive=true
thread线程运行,i=1
thread线程运行,i=2
thread线程运行,i=3
main线程运行,i=0
main线程运行,i=1
main线程运行,i=2
main方法执行完毕时,thread.isAlive=false
上面的程序和示例1的区别就是在main方法开始循环前,让main线程休眠10毫秒,目的是为了让出CPU给thread线程运行,thread线程执行完毕后,main线程开始执行循环输出1-3的数字,最后main方法执行完毕时,thread线程已经不存活了。
通过以上两个程序的演示,可以说明:
1、main方法的运行也是一个线程,也就是我们常说的主线程。
2、因为线程操作具有不确定性,所以主线程有可能最先执行完,当主线程执行完毕的时候,其他线程不会随着主线程的结束而结束,其他线程会执行完自己的操作之后才结束。(示例1可以说明这个问题)。
3、isAlive方法可以判断线程是否存活,线程存活是指线程介于启动状态和死亡状态之间的状态。