博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
Android Runnable 运行在那个线程
阅读量:4579 次
发布时间:2019-06-08

本文共 1627 字,大约阅读时间需要 5 分钟。

Runnable 并不一定是新开一个线程,比如下面的调用方法就是运行在UI主线程中的:

Handler mHandler=new Handler();mHandler.post(new Runnable(){	@Override	public void run() {		// TODO Auto-generated method stub	}});

官方对这个方法的解释如下,注意其中的:“The runnable will be run on the user interface thread. ”

boolean android.view.View .post(Runnable action)

Causes the Runnable to be added to the message queue. The runnable will be run on the user interface thread.

Parameters: 

action The Runnable that will be executed. 
Returns: 
Returns true if the Runnable was successfully placed in to the message queue. Returns false on failure, usually because the looper processing the message queue is exiting.

 

我们可以通过调用handler的post方法,把Runnable对象(一般是Runnable的子类)传过去;handler会在looper中调用这个Runnable的Run方法执行。

Runnable是一个接口,不是一个线程,一般线程会实现Runnable。

有关 Looper、Handler,Thread 关系可以看这篇博客: 

Android 的消息队列模型 

 

这里我们看代码 mHandler.post(new Runnable(){  好像是new 了一个 interface, 其实是new的一个实现Runnable的匿名内部类(Inner Anonymous Class),这是很简练的写法。

上面的代码可以看成是: new anonymousClass() implement interface{ [改写interface method]}

 

Runnable是一个接口,不是一个线程,一般线程会实现Runnable。 所以如果我们使用匿名内部类是运行在UI主线程的,如果我们使用实现这个Runnable接口的线程类,则是运行在对应线程的。

具体来说,这个函数的工作原理如下:

View.post(Runnable)方法。在post(Runnable action)方法里,View获得当前线程(即UI线程)的Handler,然后将action对象post到Handler里。在Handler里,它将传递过来的action对象包装成一个Message(Message的callback为action),然后将其投入UI线程的消息循环中。在Handler再次处理该Message时,有一条分支(未解释的那条)就是为它所设,直接调用runnable的run方法。而此时,已经路由到UI线程里,因此,我们可以毫无顾虑的来更新UI。

如下图,前面看到的代码,我们这里Message的callback为一个Runnable的匿名内部类

这种情况下,由于不是在新的线程中使用,所以千万别做复杂的计算逻辑。

参考资料:

Android中的Handler, Looper, MessageQueue和Thread 

Android系列之Message机制的灵活应用 

转载于:https://www.cnblogs.com/zsw-1993/p/4879514.html

你可能感兴趣的文章
Android八款开源游戏引擎
查看>>
cocos2d里面如何实现mvc系列
查看>>
联想拯救者15-isk安装固态硬盘与系统迁移教程
查看>>
XP更新补丁后IIS无法启动解决方法
查看>>
oracle中NULL的使用和优化
查看>>
Deepin-键盘快捷键
查看>>
忘记数据库连接字符串格式
查看>>
安卓权威编程指南-笔记 (第29章定制视图与触摸事件)
查看>>
转载Mongondb
查看>>
(转)Linux基础------Shell数值计算的几种方法
查看>>
URAL 1137Bus Routes (dfs)
查看>>
高斯消元 模版
查看>>
js 操作cookie的类
查看>>
windows下搭建vue环境
查看>>
click事件延迟300ms以及点击穿透的原因及解决
查看>>
【转】Header Only Library的介绍
查看>>
修改mysql的engine引擎
查看>>
利用拼音查询城市小结
查看>>
微信公众平台开发2-access_token获取及应用(含源码)
查看>>
JavaScript数据结构-19.拓扑排序
查看>>