在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(); //不被允许
}
}