多线程编程经常使用:Handler(处理)、Thread(线程)和Runnable这三个类
Android的cpu分配的最小单位是线程
Handler一般是在某个线程里创建的,Handler和Thread是相互绑定,一 一对应的。
Runnable是一个接口,Thread是Runnable的子类,二者都算一个进程。
启动线程方式:
1.继承Thread类,改写run方法实现一个线程
public class MyThread extends Thread {
//继承Thread类,并改写其run方法
private final static String TAG = "My Thread ===> ";
public void run(){
Log.d(TAG, "run");
for(int i = 0; i<100; i++)
{
Log.e(TAG, Thread.currentThread().getName() + "i = " + i);
}
}
}
//启动
new MyThread().start();
2.创建一个Runnable对象
public class MyRunnable implements Runnable{
private final static String TAG = "My Runnable ===> ";
@Override
public void run() {
// TODO Auto-generated method stub
Log.d(TAG, "run");
for(int i = 0; i<1000; i++)
{
Log.e(TAG, Thread.currentThread().getName() + "i = " + i);
}
}
}
//启动
new Thread(new MyRunnable()).start();
3.通过Handler启动线程
public class MainActivity extends Activity {
private final static String TAG = "UOfly Android Thread ==>";
private int count = 0;
private Handler mHandler = new Handler();
private Runnable mRunnable = new Runnable() {
public void run() {
Log.e(TAG, Thread.currentThread().getName() + " " + count);
count++;
setTitle("" + count);
// 每3秒执行一次
mHandler.postDelayed(mRunnable, 3000); //给自己发送消息,自运行
}
};
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
// 通过Handler启动线程
mHandler.post(mRunnable); //发送消息,启动线程运行
}
@Override
protected void onDestroy() {
//将线程销毁掉
mHandler.removeCallbacks(mRunnable);
super.onDestroy();
}
}
网友评论