Android—— 线程 thread 两种实现方法!(转)
原文地址:http://blog.csdn.net/boyupeng/article/details/6208072
这篇文章中有三点需要提前说明一下,
一:
在android中有两种实现线程thread的方法:
一种是,扩展java.lang.Thread类
另一种是,实现Runnable接口
二:
Thread类代表线程类,它的两个最主要的方法是:
run()——包含线程运行时所执行的代码
Start()——用于启动线程
三:
Handler 机制,它是Runnable和Activity交互的桥梁,在run方法中发送Message,在Handler里,通过不同的Message执行不同的任务。
(Handler的设计实际上是为了应用程序内其他线程和主线程进行通信,因为只有主线程才能更新UI,其他线程不行)
下面分别给出两种线程的实现方法,其一,扩展java.lang.Thread类,也就是把run()方法写到线程里面:
1 package com.my; 2 import android.app.Activity; 3 import android.os.Bundle; 4 import android.os.Handler; 5 import android.os.Message; 6 import android.util.Log; 7 import android.view.View; 8 import android.view.View.OnClickListener; 9 import android.widget.Button; 10 public class Demo_For_Copy extends Activity 11 { 12 public Button button; 13 14 public Handler mHandler=new Handler() 15 { 16 public void handleMessage(Message msg) 17 { 18 switch(msg.what) 19 { 20 case 1: 21 button.setText(R.string.text2); 22 break; 23 default: 24 break; 25 } 26 super.handleMessage(msg); 27 } 28 }; 29 30 /** Called when the activity is first created. */ 31 @Override 32 public void onCreate(Bundle savedInstanceState) 33 { 34 super.onCreate(savedInstanceState); 35 setContentView(R.layout.main); 36 button=(Button)findViewById(R.id.button); 37 38 Thread thread=new Thread(new Runnable() 39 { 40 @Override 41 public void run() 42 { 43 Log.e("1111", "111111111"); 44 // TODO Auto-generated method stub 45 Message message=new Message(); 46 message.what=1; 47 mHandler.sendMessage(message); 48 } 49 }); 50 thread.start(); 51 } 52 }
其二,实现Runnable接口,让类实现Runnable接口,然后把run方法单独提出来:
1 package com.my; 2 import android.app.Activity; 3 import android.os.Bundle; 4 import android.os.Handler; 5 import android.os.Message; 6 import android.util.Log; 7 import android.view.View; 8 import android.view.View.OnClickListener; 9 import android.widget.Button; 10 import android.widget.LinearLayout; 11 public class Title_Change_Demo extends Activity implements Runnable 12 { 13 public Button button; 14 public LinearLayout my_layout; 15 16 public Handler mHandler=new Handler() 17 { 18 public void handleMessage(Message msg) 19 { 20 switch(msg.what) 21 { 22 case 1: 23 button.setText(R.string.text2); 24 break; 25 default: 26 break; 27 } 28 my_layout.invalidate(); 29 super.handleMessage(msg); 30 } 31 }; 32 33 /** Called when the activity is first created. */ 34 @Override 35 public void onCreate(Bundle savedInstanceState) 36 { 37 super.onCreate(savedInstanceState); 38 setContentView(R.layout.main); 39 40 button=(Button)findViewById(R.id.button); 41 my_layout=(LinearLayout)findViewById(R.id.my_layout); 42 43 Thread thread=new Thread(this); 44 thread.start(); 45 } 46 47 @Override 48 public void run() 49 { 50 Log.e("ok", "111111111"); 51 // TODO Auto-generated method stub 52 Message message=new Message(); 53 message.what=1; 54 mHandler.sendMessage(message); 55 } 56 } 57