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

4 篇文章 0 订阅
3 篇文章 0 订阅

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

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

HandlerThread thread = new HandlerThread("custom1");
thread.start();






  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值