Android Thread 介紹與執行個體_Android

來源:互聯網
上載者:User

Android中很重要的一個機制就是線程+訊息,當然線程並不是android專屬的,下面,簡單的說說使用線程的時候應該注意的地方

我們採用最簡單的方法來建立一個android的線程+訊息的例子

1.Thread + Handler

[java]

複製代碼 代碼如下:

package com.example.test_thread;

import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.widget.TextView;

public class MainActivity extends Activity {

    TextView mTextView = null;
//  static TextView mTextView = null; 
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        mTextView = (TextView)findViewById(R.id.textview);
        Thread th = new Thread(new Runnable() {

            @Override
            public void run() {
                // TODO Auto-generated method stub 
                for(int i = 0;i<1000;i++)
                {
                    try {
                        Thread.sleep(500);
                        System.out.println("Thread running :"+i+"!");
                        Message msg = new Message();
                        msg.what = i;
                        mHandler.sendMessage(msg);
                    } catch (InterruptedException e) {
                        // TODO Auto-generated catch block 
                        e.printStackTrace();
                    }
                }
            }
        });
        th.start();

    }
    public Handler mHandler = new Handler(){
//    public static Handler mHandler = new Handler(){ 

        @Override
        public void handleMessage(Message msg) {
            // TODO Auto-generated method stub 
            super.handleMessage(msg);

            mTextView.setText(String.valueOf(msg.what));
        }

    };

}

package com.example.test_thread;

import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.widget.TextView;

public class MainActivity extends Activity {

 TextView mTextView = null;
// static TextView mTextView = null;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        mTextView = (TextView)findViewById(R.id.textview);
        Thread th = new Thread(new Runnable() {

   @Override
   public void run() {
    // TODO Auto-generated method stub
    for(int i = 0;i<1000;i++)
    {
     try {
      Thread.sleep(500);
      System.out.println("Thread running :"+i+"!");
      Message msg = new Message();
      msg.what = i;
      mHandler.sendMessage(msg);
     } catch (InterruptedException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
     }
    }
   }
  });
        th.start();

    }
    public Handler mHandler = new Handler(){
//    public static Handler mHandler = new Handler(){

  @Override
  public void handleMessage(Message msg) {
   // TODO Auto-generated method stub
   super.handleMessage(msg);

   mTextView.setText(String.valueOf(msg.what));
  }

    };

}

當我們用以上方式建立線程時,進入應用之後,線程開始運行,Handler接收訊息改變UI中的TextView,此時一切正常

當按下退出時,程式退出,但是程式進程還在stack中,因此主線程之子線程,也就是我們定義的th(th_1)不會退出,此時,在log資訊中可以看到,system.out還在print數字

當再次進入程式的時候,可以看到,log中列印的資訊double,但是UI會按照新線程(th_2)的次序改變

此時th_1仍在運行,th_1使用的 handler_1也在運行,只不過上一個Activity的狀態已經是finish,因此不會改變UI  this ->mFinished= true

其實只要th_1中有關於上一個Activity的引用,那麼Activity就不會銷毀,java的機制就是這樣,這是我們推薦的線程機制,下面著重說一下可能遇到的問題

2.同樣是剛剛的例子,我們將Handler定義成static

[java]
public static Handler mHandler = new Handler(){

public static Handler mHandler = new Handler(){此時,在退出應用再重新進入時,由於Handler並不會有新的執行個體,因此,th_1與th_2同時發訊息給一個static Handler 或者說是指向了同一塊記憶體地區,這時就會出現TextView上的數字來回跳的現象

3.這樣也可以

使用static定義Handler也不是不可以,只要在Activity的onCreate()中重新執行個體一個Handler,這樣,JVM分配另一塊記憶體給新的Handler,這樣運行就正常了

[java]

複製代碼 代碼如下:

package com.example.test_thread;

import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.widget.TextView;

public class MainActivity extends Activity {

    public Handler mHandler = null;
    TextView mTextView = null;
//  static TextView mTextView = null; 
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        mTextView = (TextView)findViewById(R.id.textview);
        mHandler = new TestHandler();
        Thread th = new Thread(new Runnable() {

            @Override
            public void run() {
                // TODO Auto-generated method stub 
                for(int i = 0;i<1000;i++)
                {
                    try {
                        Thread.sleep(500);
                        System.out.println("Thread running :"+i+"!");
                        Message msg = new Message();
                        msg.what = i;
                        mHandler.sendMessage(msg);
                    } catch (InterruptedException e) {
                        // TODO Auto-generated catch block 
                        e.printStackTrace();
                    }
                }
            }
        });
        th.start();

    }
    class TestHandler extends Handler
    {
        @Override
        public void handleMessage(Message msg) {
            // TODO Auto-generated method stub 
            super.handleMessage(msg);
            System.out.println("Handler running :"+msg.what+"!");
            mTextView.setText(String.valueOf(msg.what));
        }

    }
}

package com.example.test_thread;

import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.widget.TextView;

public class MainActivity extends Activity {

    public Handler mHandler = null;
 TextView mTextView = null;
// static TextView mTextView = null;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        mTextView = (TextView)findViewById(R.id.textview);
        mHandler = new TestHandler();
        Thread th = new Thread(new Runnable() {

   @Override
   public void run() {
    // TODO Auto-generated method stub
    for(int i = 0;i<1000;i++)
    {
     try {
      Thread.sleep(500);
      System.out.println("Thread running :"+i+"!");
      Message msg = new Message();
      msg.what = i;
      mHandler.sendMessage(msg);
     } catch (InterruptedException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
     }
    }
   }
  });
        th.start();

    }
    class TestHandler extends Handler
    {
  @Override
  public void handleMessage(Message msg) {
   // TODO Auto-generated method stub
   super.handleMessage(msg);
   System.out.println("Handler running :"+msg.what+"!");
   mTextView.setText(String.valueOf(msg.what));
  }

    }
}


當然,總的來說Java還是不推薦使用static變數的,這本身也不符合物件導向的變成思想,所以,建議除了一些final值,盡量還是多使用訊息機制來解決問題,維護也輕鬆些

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.