如何创建线程?如何创建扩展Thread类?

大多数情况,通过实例化一个Thread对象来创建一个线程。Java定义了两种方式:
· 实现Runnable 接口。
· 可以继承Thread类。
前一篇文章介绍了下面介绍了实现Runnable 接口,这篇文章将会介绍Thread。

扩展Thread

创建线程的另一个途径是创建一个新类来扩展Thread类,然后创建该类的实例。

当一个类继承Thread时,它必须重载run()方法,这个run()方法是新线程的入口。它也必须调用start()方法去启动新线程执行。下面用扩展thread类重写前面的程序:

// Create a second thread by extending Thread 
class NewThread extends Thread { 
 NewThread() { 
 // Create 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 thread."); 
 } 
} 
class ExtendThread { 
 public static void main(String args[]) { 
 new NewThread(); // create 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."); 
 } 
}

该程序生成和前述版本相同的输出。子线程是由实例化NewThread对象生成的,该对象从Thread类派生。注意NewThread 中super()的调用。该方法调用了下列形式的Thread构造函数:

public Thread(String threadName) 

这里,threadName指定线程名称。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值