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(); // 執行緒的啟動

第二種啟用方式建立一個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(); // 執行緒的啟動

建立點選事件啟動執行緒
btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public
void onClick(View v) { new Thread(new Runnable() { @Override public void run() { try { ... } catch (Exception e) { e.printStackTrace(); } } }).start(); } });

第三種啟用方式通過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();       
         }       

}