Android 启用线程的方法

来源:互联网 发布:mysql nvl 编辑:程序博客网 时间:2024/06/03 16:01

1,首先第一种启用方法是通过继承Thread类,并改写run方法来实现一个线程


public class ThreadDemo extends Thread {  


    //继承Thread类,并改写其run方法        

    private final static String TAG = "Thread Demo";      

    public void run(){  

        Log.d(TAG, "run");  

        for(int i = 0; i<100; i++)  

        {  

            Log.e(TAG, Thread.currentThread().getName() + "i =  " + i);  

        }  

    }  

}

启动

new ThreadDemo().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<100; 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();
            }
        });


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();       

         }       


}




原创粉丝点击