在主线程上从辅助线程运行代码? [英] Running code on the main thread from a secondary thread?
问题描述
这是一个一般的Java问题,而不是一个Android首先!
This is a general Java question and not an Android one first off!
我想知道如何在主线程上运行代码,从上下文的次级螺纹。例如:
I'd like to know how to run code on the main thread, from the context of a secondary thread. For example:
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。
That sort of thing - I realise my example is a little poor since in Java you don't need to be in the main thread to print something out, and that Swing has an event queue also - but the generic situation where you might need to run say a Runnable on the main thread while in the context of a background thread.
编辑:为了比较,这里我将如何在Objective-C中执行:
For comparison - here's how I'd do it in 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
});
});
提前感谢!
推荐答案
没有通用的方式只是发送一些代码到另一个正在运行的线程,说嘿,你,这样做。您需要将主线程置于一个具有接收工作并等待工作的机制的状态。
There is no universal way to just send some code to another running thread and say "Hey, you, do this." You would need to put the main thread into a state where it has a mechanism for receiving work and is waiting for work to do.
这里有一个简单的示例,主线程等待从其他线程接收工作,并在它到达时运行它。显然你想添加一个方法来实际结束程序等等...
Here's a simple example of setting up the main thread to wait to receive work from other threads and run it as it arrives. Obviously you would want to add a way to actually end the program and so forth...!
public static final BlockingQueue<Runnable> queue = new LinkedBlockingQueue<Runnable>();
public static void main(String[] args) throws Exception {
new Thread(new Runnable(){
@Override
public void run() {
final int result;
result = 2+3;
queue.add(new Runnable(){
@Override
public void run() {
System.out.println(result);
}
});
}
}).start();
while(true) {
queue.take().run();
}
}
这篇关于在主线程上从辅助线程运行代码?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!