一斤十两是哪年:JAVA:线程的生命周期是什么

来源:百度文库 编辑:杭州交通信息网 时间:2024/04/29 03:57:47

1、一个线程的的生命周期可以分成两阶段:生存周期和死亡周期,其中生存周期又包括运行状态和等待状态.当创建一个新线程后,这个线程就进入了排队状态,当线程中的方法start()被调用时,线程就进入生存周期,这时它的方法isAlive()始终返回真值,直至线程进入死亡状态。
2、有两种方法可以实现线程,一种是扩展java.lang.Thread类,另一种是通过java.lang.Runnable接口
3、范例
import java.awt.*;
class Sample1{
public static void main(String[] args){
Mythread test1=new Mythread(1);
Mythread test2=new Mythread(2);
test1.start();
test2.start();
}
}
class Mythread extends Thread {
int id;
Mythread(int i)
{ id=i;}
public void run() {
int i=0;
while(id+i==1){
try {sleep(1000);
} catch(InterruptedException e) {}
}
System.out.println(“The id is ”+id);
}