Moosphan / Android-Daily-Interview

:pushpin:每工作日更新一道 Android 面试题,小聚成河,大聚成江,共勉之~

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

2019-05-09:谈谈你对 Activity.runOnUiThread 的理解?

Moosphan opened this issue · comments

2019-05-09:谈谈你对 Activity.runOnUiThread 的理解?

其实就是判断下线程,调用handler。这有什么好问的。。。
可以看出问的人也不怎么样。
一个简单的方法封装,然后把这方法放到 Activity里。
你别在问我哪来的 handler

commented

一般是用来将一个runnable绑定到主线程,在runOnUiThread源码里面会判断当前runnable是否是主线程,如果是直接run,如果不是,通过一个默认的空构造函数handler将runnable post 到looper里面,创建构造函数handler,会默认绑定一个主线程的looper对象

答题者------之前没太关注过这个,今天搜了搜相应的文章,就算是查漏补缺,感谢作者提出的问题;
文章地址----https://www.jianshu.com/p/e39449026f21

public final void runOnUiThread(Runnable action) {
if (Thread.currentThread() != mUiThread) {
mHandler.post(action);
} else {
action.run();
}
}

谈一下个人理解 欢迎指正

其实楼上的源码已经解释的很明白了,
当前线程不是ui线程,即发送post消息切换到ui线程(这个和sendMessage是有区别的,sendMessage是在非ui线程发送消息,这个在当前线程发送消息,然后因为activity初始化的时候就有looper、和MessageQueue,就能直接处理消息,从而将mUiThread切换到当前线程,再次执行就直接进行action.run())

是ui线程,即直接实现方法

打卡打卡

以后写篇博客 把Handler这块好好梳理一下

public final void runOnUiThread(Runnable action) {
if (Thread.currentThread() != mUiThread) {
mHandler.post(action);
} else {
action.run();
}
}

判断当前是不是 ui 线程,如果是就直接运行,否则就通过handler的post方法切换到主线程

@Override
public final void runOnUiThread(Runnable action) {
    if (Thread.currentThread() != mUiThread) {
        mHandler.post(action);
    } else {
        action.run();
    }
}

先判断是当前的线程是不是 UI 线程,如果不是 UI 线程,就执行 Activity 中的 Handler 对象 mHandler.post() 方法,在主线程中执行;如果是在主线程,则直接在主线程中执行 Runnable 中的 run() 方法。

参考自:Android 多线程之 Handler 源码分析

runOnUiThread用于切换到主线程更新UI 其内部判断当前线程是否为UI主线程 如果不是则通过handle post方法在主线程中执行