安卓中,实现多线程有两种方法,一种是扩展Thread类,一种是实现Runnable接口(一般常用Runnable接口).然后通过Handler机制与主线程通信
第一种,thread类
可以通过继承thread类,复写run()方法,或者直接扩展,也就把run()方法写到线程里
1:
package org.thread.demo;
class MyThread extends Thread{
private String name;
public MyThread(String name) {
super();
this.name = name;
}
public void run(){
for(int i=0;i<10;i++){
System.out.println("线程开始:"+this.name+",i="+i);
}
}
}
package org.thread.demo;
public class ThreadDemo01 {
public static void main(String[] args) {
MyThread mt1=new MyThread("线程a");
MyThread mt2=new MyThread("线程b");
mt1.run();
mt2.run();
}
}
2:
Thread thread=new Thread(new Runnable()
{
@Override
public void run()
{
Log.e("1111", "111111111");
// TODO Auto-generated method stub
}
});
thread.start();
}
第二种方法,Runnable接口
class MyThread implements Runnable{
private String name;
public MyThread(String name) {
this.name = name;
}
public void run(){
for(int i=0;i<100;i++){
System.out.println("线程开始:"+this.name+",i="+i);
}
}
}
需要注意的是,Thread类是Runnable的子类,同时两者有一定区别,开发中一般优先使用Runnable
|