android系统中的多线程(一): 关于在android中启动线程以及线程间的交互

来源:互联网 发布:sql 重复数据 编辑:程序博客网 时间:2024/05/20 04:47

http://blog.csdn.net/crystal923129/article/details/6739443

android中,一个应用开始运行的时候,系统将创建一个线程名为main,同时也称作UI thread.同一进程中的所有组件都在main线程中创建,并且接收用户的操作.如果阻塞该线程超过5s将弹出ANR对话框。同时androidUI工具包是非线程安全的。

因而有两点必须注意:

  1. 不要阻塞UI thread
  1. 不要在其它线程中操作UI

也因此推导出两个知识块:

  1. 对于需要长时间执行的任务需要启动work thread,在android中启动work thread的方法是什么?
  1. 在work thread 如何对UI进行更新和设置


Java传统方法 Thread / Runnable 继承Thread实现run

创建Runnable,实现run,实例作为参数创建Thread


使用Handler进行线程间交互

每一个Handler的实例都与唯一的线程以及该线程的message queue 相关联。

默认情况下handler与创建它的线程相关联,但是也可以在构造函数中传入Looper实例,以绑定到其它线程。

Handler的作用就是将messagerunnable对象发送到与之相关联的message queue中,并且从queue中获取他们进行处理。

这就起到了将数据在线程中传递的目的,实现了线程间的交互。



    • 对于Handler启动runnable在下面的关于定时和周期性执行中进行详细介绍

    • 关联于main线程的handler,实现了帮助work thread 更新UI的目的,在关于在work thread中对UI进行更新和设置中详细介绍

    • 为了使handler关联于work thread而非main 线程,需要在构造函数时给定Looper实例

Looper用于执行一个线程的message 循环。通过它handler可以关联上相应的thread及其message queue。默认情况下,thread是没有Looper对象的,需要自己在thread中添加该对象,并调用其 prepare() 和 loop()方法。不考虑同步的情况下简单实现一个有Loop的thread:
[java] view plaincopy
  1. class LoopThread extends Thread{  
  2.      public Looper MyLooper;  
  3.       public LoopThread(String name){  
  4.            super(name);  
  5.            MyLooper = Looper.myLooper();  
  6.            Log.w(TAG, "in thread init: loop  "+MyLooper.getThread().getName());  //main  
  7.       }  
  8.     public void run(){  
  9.            Log.w(TAG, "inthread :"+Thread.currentThread().getName());   //main  
  10.            Looper.prepare();  
  11.            MyLooper = Looper.myLooper();  
  12.            Log.w(TAG, "inthread run: loop "+MyLooper.getThread().getName());   //name  
  13.            Looper.loop();  
  14.            }  
  15.     }  
  16. LoopThread thread1 = new LoopThread("custom2");  
  17. thread1.start();  
  18. Handler handler = new Handler(thread1.MyLooper);  

其中有2点值得注意:
  1. Looper 在调用prepare() 之后才指向当前thread,之前是指向main thread的
  2. handler必须在thread调用start方法(运行run)之后才能获取looper,否则为空,因为prepare需要在run方法中调用

    • 为了方面使用带有Looper的Thread,android实现了HandlerThread

[java] view plaincopy
  1. HandlerThread thread = new HandlerThread("custom1");  
  2. thread.start();