分享

Android 中三种使用线程的方法

 joy_chen 2014-03-18

通过继承Thread类,并改写run方法来实现一个线程

 

  1. public class MyThread extends Thread {  
  2.       
  3.     //继承Thread类,并改写其run方法  
  4.       
  5.     private final static String TAG = "My Thread ===> ";  
  6.       
  7.     public void run(){  
  8.         Log.d(TAG, "run");  
  9.         for(int i = 0; i<100; i++)  
  10.         {  
  11.             Log.e(TAG, Thread.currentThread().getName() + "i =  " + i);  
  12.         }  
  13.     }  
  14. }  

 

启动线程:

 

  1. new MyThread().start();  

 

2.创建一个Runnable对象

 

  1. public class MyRunnable implements Runnable{  
  2.     private final static String TAG = "My Runnable ===> ";  
  3.       
  4.     @Override  
  5.     public void run() {  
  6.         // TODO Auto-generated method stub  
  7.         Log.d(TAG, "run");  
  8.         for(int i = 0; i<1000; i++)  
  9.         {  
  10.             Log.e(TAG, Thread.currentThread().getName() + "i =  " + i);  
  11.         }  
  12.     }  
  13. }  

 

启动线程:

 

  1. // providing a new Thread instance with a Runnable object during its creation.  
  2.         new Thread(new MyRunnable()).start();  

 

3.通过Handler启动线程

 

  1. public class MainActivity extends Activity {  
  2.       
  3.     private final static String TAG = "UOfly Android Thread ==>";  
  4.     private int count = 0;  
  5.     private Handler mHandler = new Handler();  
  6.     private Runnable mRunnable = new Runnable() {  
  7.         public void run() {  
  8.             Log.e(TAG, Thread.currentThread().getName() + " " + count);  
  9.             count++;  
  10.             setTitle("" + count);  
  11.             // 每3秒执行一次  
  12.             mHandler.postDelayed(mRunnable, 3000);  
  13.         }  
  14.     };  
  15.     /** Called when the activity is first created. */  
  16.     @Override  
  17.     public void onCreate(Bundle savedInstanceState) {  
  18.         super.onCreate(savedInstanceState);  
  19.         setContentView(R.layout.main);  
  20.         // 通过Handler启动线程  
  21.         mHandler.post(mRunnable);  
  22.     }  
  23.       
  24.       @Override      
  25.          protected void onDestroy() {       
  26.              //将线程销毁掉       
  27.              mHandler.removeCallbacks(mRunnable);       
  28.              super.onDestroy();       
  29.          }       
  30.       
  31. }  

 http://www.cnblogs.com/u0fly/archive/2011/01/25/1944645.html

    本站是提供个人知识管理的网络存储空间,所有内容均由用户发布,不代表本站观点。请注意甄别内容中的联系方式、诱导购买等信息,谨防诈骗。如发现有害或侵权内容,请点击一键举报。
    转藏 分享 献花(0

    0条评论

    发表

    请遵守用户 评论公约

    类似文章 更多