第一种:继承Thread类,实现run()方法;调用父类Thread的start()方法,启动线程。
package com.example.android_thread;
import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.widget.TextView;
public class MainActivity extends Activity {
TextView tv;
MyHandler myHandler;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tv = (TextView)findViewById(R.id.tv);
new MyThread("thread1").start();
new MyThread("thread2").start();
myHandler = new MyHandler();
}
class MyThread extends Thread{
String name;
public MyThread(String t1){
name=t1;
}
public void run(){
Message msg=new Message();
Bundle b=new Bundle();
b.putString("text", name);
msg.setData(b);
myHandler.sendMessage(msg);
}
}
class MyHandler extends Handler{
public MyHandler(){
}
public void handleMessage(Message msg){
super.handleMessage(msg);
Bundle b=msg.getData();
String str=b.getString("text");
tv.setText(str);
Log.i("xxx",str);
}
}
}
第二种:继承Runnable接口,实现run()方法;把对象传递给Thread的带Runnable参数的构造函数,然后调用Thread的start()方法,启动线程。---------------->一般使用这种方式实现多线程
继承Thread类的缺点是,由于java不支持多重继承,因此只能单一继承
但是实现Runnable接口就不一样了。可以实现多个接口。
package com.example.android_thread;
import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.widget.TextView;
public class MainActivity extends Activity {
TextView tv;
MyHandler myHandler;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tv = (TextView)findViewById(R.id.tv);
myHandler = new MyHandler();
//区别1,这里也可以修改一下
new Thread(new MyThread("thread1")).start();
new Thread(new MyThread("thread2")).start();
}
//区别2,这里可以修改一下,
class MyThread implements Runnable{
String name;
public MyThread(String t1){
name=t1;
}
public void run(){
Message msg=new Message();
Bundle b=new Bundle();
b.putString("text", name);
msg.setData(b);
myHandler.sendMessage(msg);
}
}
class MyHandler extends Handler{
public MyHandler(){
}
public void handleMessage(Message msg){
super.handleMessage(msg);
Bundle b=msg.getData();
String str=b.getString("text");
tv.setText(str);
Log.i("xxx",str);
}
}
}
更简练的一种写法:
在Runnable或者Thread的构造函数中实现线程的启动,实现的主要代码
可以修改为:
new Thread("thread1")
new Thread("thread2")
class MyThread implements Runnable{
String name;
Thread thread;
public MyThread(String t1){
name=t1;
thread(this).start()
}
public void run(){
Message msg=new Message();
Bundle b=new Bundle();
b.putString("text", name);
msg.setData(b);
myHandler.sendMessage(msg);
}
}