创建线程的另一个途径是创建一个新类来扩展Thread类,然后再创建该类的实例。当一个类继承Thread时。它必须重载run()方法,这个run()方法是新线程的入口,同时,它也必须调用start()方法去启动新线程的执行,下面用扩展thread类重写上一个的程序,
public class thread2 {
public static void main(String args[]){
new NewThread(); //creat a new thread
try{
for(int i=5;i>0;i--)
{
System.out.println("main thread:"+i);
Thread.sleep(1000);
}
}
catch(InterruptedException e){
System.out.println("main thread interrupted.");
}
System.out.println("main thread exiting.");
}
}
//creat a second thread by extending thread
class NewThread extends Thread{
NewThread(){
//cread a new ,second thread
super("demo Thread");
System.out.println("child thread:"+this);
start(); //start the thread
}
//this is the entry point for the second thread
public void run()
{
try{
for(int i=5;i>0;i--)
{
System.out.println("child thread:"+i);
Thread.sleep(500);
}
}
catch(InterruptedException e){
System.out.println("child interrupted.");
}
System.out.println("Exiting child interrupted.");
}
}
该程序的运行结果和前面的版本相同,子线程是由实例化NewThread对象生成的,该对象从thread类派生。请注意NewThread中的super()方法的调用,该方法调用了下列形式的Thread构造函数:
public Thread(String threadName)
这里,threadName用于指定线程名称。代码中的super即指Thread。