从辅助线程在主线程上运行代码? [英] Running code on the main thread from a secondary thread?

查看:31
本文介绍了从辅助线程在主线程上运行代码?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是一个通用的 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屋!

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