Android中线程的使用很重要,有时候线程使用不好直接导致线程卡死,软件崩溃。下面分享一下我再开发时对线程的理解,如果有错误还希望大家多多指正。
当一个Activity被创建之后,一个线程就算开启了,也就是主线程或者UI线程,主线程中只负责更新界面,而子线程中才会去执行一些复杂的业务。
在Android中线程的使用我用的最多的是这三种:Thread、Runnable、Handler
1.Thread 通过集成Thread用run方法来实现线程
public class MyThread extends Thread {
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);
}
}
}
用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);
}
}
}
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();
}
}
这三种线程通常使用的比较多~~~