首先,这是一个普遍的Java问题,而不是Android问题!
我想知道如何从辅助线程的上下文中在主线程上运行代码。例如:
new Thread(new Runnable() {
public void run() {
//work out pi to 1,000 DP (takes a while!)
//print the result on the main thread
}
}).start();
那种情况——我意识到我的例子有点差,因为在Java中你不需要在主线程中打印出东西,并且Swing也有一个事件队列。但是一般情况下,当你需要在后台线程的上下文中运行一个可运行对象(Runnable)时,可能需要在主线程上运行。
补充说明:为了比较,在Objective-C中我会这样做:
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0UL), ^{
//do background thread stuff
dispatch_async(dispatch_get_main_queue(), ^{
//update UI
});
});
提前感谢!