thread和runnable的区别

在java中现在很多操作都不能在主线程中执行,因为主线程的耗时操作过多将导致应用无响应。在android里面就会产生ANR(输入时间响应超过5s,

意向接收超过10s),所以android里面建议很多操作都放在子线程中执行,特别耗时的操作(如本地读写,数据库读写,网络请求等)放在子线程中执行。

在java中有两个类可以开子线程,即thread和runnable现在说说他们的区别:

一、各自的实现过程。

thread:

<pre name="code" class="java"><span style="font-family: Arial, Helvetica, sans-serif;">public class MyThread extends Thread{</span>
private int count;public MyThread(int count){this.count=count;}@overridepublic void run(){ System.out.println(“thread number”+count);}}public class test{public static void main(String[] args){MyThread thread=new MyThread();thread.start();}}}

 


Runnable:


System.out.println("the thread number"+count);
}
}
}
}

public class test{
public static void main(String[] args){
Thread t=new Thread(new MyThread);
t.start();
}
}

第一个区别:

1、Runnable是接口,是java版本的多继承实现,可以由多个子类继承,更加灵活。而Thread是类,不能实现多继承。

2、多任务资源共享问题。

第一个不多讲,主要是第二个问题;

thread:

//继承于Thread实现买票机器
public class ticketSell extends Thread{
private int count=10;
@override
public void run(){
System.out.println("买票中,剩下"+count--);
}

}

public  class test{
public static void main(String[] args){
(new tickSell()).start();   //开启第一个买票线程
(new tickSell()).start();   //开启第二个卖票线程
//上面的结果是同样的票会被卖两次。
}
}
runnable:

public class tickSell implements Runnable{
private int count;
public tickSell(int count){
this.count=count;
}
@override
public void run(){
for(int i=0;i<10;i++){
System.out.println("剩下票数量"+count);
}
}
}

public class test{
public static void main(String[] args){
ticketSell t=new ticketSell();
(new Thread(t)).start();
(new Thread(t)).start();  //不被允许
}
}




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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值