JAVA 线程的两种基本实现方法(继承Thread类和实现Runnable接口)

线程的两种基本实现方法:

1.继承Thread类
2.实现Runnable接口

推荐使用Runnable接口,基于以下四点:

 1.使用 Runnable 接口适合多个相同程序代码的线程去处理同一资源的情况,
    把虚拟CPU(线程)同程序的代码,数据有效的分离,较好地体现了面向对象的设计思想。 
 2.继承Thread类有一个缺点就是单继承,而实现Runnable接口则弥补了它的缺点,可以实现多继承。
 3.有利于程序的健壮性,代码能够被多个线程共享,代码与数据是独立的。
 4.使用 Runnable 接口来实现多线程使得我们能够在一个类中包容所有的代码,有利于封装。

具体代码实现:

//线程的测试类
public class testThread{
public static void main(String args[]){
Thread    thread1=new threadOne("one");
Thread    thread2=new threadTwo("two");
thread1.start();
thread2.start();
}
}

//方法一
//通过继承Thread类来构建线程
//需要覆盖run()方法
class threadOne extends Thread{
String name;
threadOne(String name)
{
this.name=name;
}
public void run()
{
for(int i=0;i<=9;i++)
System.out.println("Current thread is "+name);
}
}

//方法二
//通过实现Runnable接口来构建线程
//需要覆盖run()方法
class threadTwo implements Runnable{
String name;
threadTwo(String name)
{
this.name=name;
}
public void run()
{
for(int i=0;i<=9;i++)
System.out.println("Current thread is "+name);
}
}


  • 3
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值