您的位置:首页 > 移动开发 > Android开发

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

2013-01-29 14:43 465 查看
http://blog.csdn.net/crystal923129/article/details/6739443

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

不要阻塞UI
thread

不要在其它线程中操作UI

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

对于需要长时间执行的任务需要启动work thread,在android中启动work thread的方法是什么?

在work thread 如何对UI进行更新和设置

[b]Java传统方法 Thread / Runnable 继承Thread实现run[/b]
创建Runnable,实现run,实例作为参数创建Thread



使用Handler进行线程间交互

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

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

Handler的作用就是将message或runnable对象发送到与之相关联的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

class LoopThread extends Thread{

public Looper MyLooper;

public LoopThread(String name){

super(name);

MyLooper = Looper.myLooper();

Log.w(TAG, "in thread init: loop "+MyLooper.getThread().getName()); //main

}

public void run(){

Log.w(TAG, "inthread :"+Thread.currentThread().getName()); //main

Looper.prepare();

MyLooper = Looper.myLooper();

Log.w(TAG, "inthread run: loop "+MyLooper.getThread().getName()); //name

Looper.loop();

}

}

LoopThread thread1 = new LoopThread("custom2");

thread1.start();

Handler handler = new Handler(thread1.MyLooper);

其中有2点值得注意:

Looper 在调用prepare() 之后才指向当前thread,之前是指向main thread的
handler必须在thread调用start方法(运行run)之后才能获取looper,否则为空,因为prepare需要在run方法中调用

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

[java] view
plaincopy

HandlerThread thread = new HandlerThread("custom1");

thread.start();
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐