Android的runOnUiThread执行顺序 [英] Android runOnUiThread execution sequence

查看:588
本文介绍了Android的runOnUiThread执行顺序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

runOnUiThread(new Runnable(){

    @Override
    public void run() {

         System.out.println("print out from runOnUIThread.");
    }

});

System.out.println("print out in main thread.");



**Output:**
print out from runOnUIThread.
print out in main thread.



基本上 runOnUiThread 将在后台线程中使用,我做这仅用于测试。



Basically runOnUiThread will be used in background thread, I am doing this for testing only.

在code以上的活动 的onCreate 方法。

The code above execute in Activity onCreate method.

从输出中,结果不是我所期望的。我在想,既然 runOnUiThread 发布可运行块为主线,以及当前执行上下文是主线程已经,所以 runOnUiThread 后应计划,在主线程打印出,但为什么结果不显示这样呢?难道我除preT是错误的?任何人都可以亲切地解释一下吗?


修改

哦,我应该首先阅读API。无论如何,为什么这让我困惑是因为,在iOS系统中,类似的机制,不同的表现:

From the output, the result is not what I expect. I am thinking that, since runOnUiThread post the runnable block to main thread, and the current execution context is in the main thread already, so runOnUiThread should be scheduled after "print out in main thread", but why the result doesn't show like that? Do I interpret it wrongly? Can anyone kindly explain?




Oh I should read the API first. Anyway, why this confuse me is because, in iOS, the similar mechanism behave differently:

dispatch_async(dispatch_get_main_queue(), ^{
           NSLog(@"Main thread from Dispatch.");
});

NSLog(@"Main thread.");

的上面的输出是相反的。

The output of above is reversed.

推荐答案

runOnUiThread:运行在UI线程上指定的操作。 如果当前线程是UI线程,则动作立即执行。如果当前线程不是UI线程,该操作被张贴到UI线程的事件队列。

runOnUiThread: Runs the specified action on the UI thread. If the current thread is the UI thread, then the action is executed immediately. If the current thread is not the UI thread, the action is posted to the event queue of the UI thread.

活动的onCreate()方法还运行在UI线程。首页 runOnUiThread code将运行,那么剩下的code。

Activity onCreate() method also runs in UI thread. First runOnUiThread code will run then rest of the code.

这篇关于Android的runOnUiThread执行顺序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆