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
将在后台线程中使用,我仅用于测试。
上面的代码在Activity
onCreate
方法中执行。
从输出来看,结果不是我期望的。我在想,既然runOnUiThread
将runnable
块发布到主线程中,并且当前的执行上下文已经在主线程中,那么runOnUiThread
应该在“在主线程中打印”之后进行调度,但是为什么结果不会这样显示?我会误解吗?谁能解释一下?
编辑:
哦,我应该先阅读API。无论如何,为什么让我感到困惑是因为在iOS中,类似的机制的行为有所不同:
dispatch_async(dispatch_get_main_queue(), ^{
NSLog(@"Main thread from Dispatch.");
});
NSLog(@"Main thread.");
上面的输出被反转。
runOnUiThread:
在UI线程上运行指定的操作。如果当前线程是UI线程,则立即执行该操作。如果当前线程不是UI线程,则将操作发布到UI线程的事件队列。
Activity onCreate()
方法也可以在UI线程中运行。先runOnUiThread
运行代码,然后运行其余代码。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句