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);
- }
- }
- }
启动线程:
- // providing a new Thread instance with a Runnable object during its creation.
- 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();
- }
- }