Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Open
Moosphan opened this issue May 9, 2019 · 7 comments
Open

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

Moosphan opened this issue May 9, 2019 · 7 comments
Labels

Comments

@Moosphan
Copy link
Owner

Moosphan commented May 9, 2019

No description provided.

@Moosphan Moosphan added the 线程 label May 9, 2019
@tangzejin921

This comment has been minimized.

@YangSimon
Copy link

YangSimon commented May 9, 2019

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

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

@guosen
Copy link

guosen commented May 9, 2019

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

@yangfanggang
Copy link

谈一下个人理解 欢迎指正

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

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

打卡打卡

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

@LvKang-insist
Copy link

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

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

@smartsean
Copy link

@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 源码分析

@mlinqirong
Copy link

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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

8 participants