等待线程完成执行

发布于 2024-11-03 09:07:03 字数 427 浏览 0 评论 0原文

Java新手在这里。我正在使用第三方库,它为我提供了一个函数,例如 F(),其输出决定了我的逻辑。所以我需要它的结果来在我的代码中进一步进行。

问题是 F() 执行一些 I/O,因此会产生一个线程来执行该功能。他们给了我一些回调来实现,这些回调被调用以从线程返回状态/值。这很好,只是函数 F() 立即返回并且我的代码的其余部分继续运行。我不希望这样,因为我必须根据 F() 的结果分配一些对象,所以我真的想等待 F() 真正完成。

这应该是人们经常遇到的问题。处理这个问题的正确方法是什么?是我的设计有问题还是第三方库有问题?还是我对图书馆不太了解?

为了完整起见,我正在开发一个 Android 应用程序,库是 facebook sdk。该函数是单点登录函数authorize()。尽管这是一个很普遍的问题,但我认为最好在 Java 论坛中解决。

感谢您的任何帮助。 -P

Java newbie here. I am using a third party library which gives me a function, say F(), the output of which dictates my logic. So I need the result of it to proceed further in my code.

The problem is F() does some I/O and so spawns off a thread to do the functionality. They gave me a few callbacks to implement which are called to return the status/values from the thread. This is fine except that the function F() returns immediately and the rest of my code keeps running. I don't want that as I have to allocate some objects based on the outcome of F() and so I really want to wait for F() to really finish.

This should be a problem people run into quite often. What is the correct way to deal with this? Is it a problem in my design or the third party library? Or did I not understand the library very well?

For the sake of completeness I am working on an android app and the library is the facebook sdk. The function is the single sign-on function authorize(). Though this is a generic enough problem that I thought is best addressed in the Java forum.

Thanks for any help.
- P

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

吃颗糖壮壮胆 2024-11-10 09:07:03

我不熟悉 facebook SDK,但处理此类异步操作的正常机制是 Callable<>或未来<>接口:您将创建一个服务执行器,传入 Callable<>或 Future<>,然后继续您的代码。

可以从Future<>中找到一个例子。 javadoc: http://download.oracle。 com/javase/6/docs/api/java/util/concurrent/Future.html

另请参阅 StackOverflow 问题/答案 如何从 Callable() 返回对象

I'm not familiar with the facebook SDK, but the normal mechanism to handle async operations like this is the Callable<> or Future<> interface: you'd create a service executor, pass in the Callable<> or Future<>, and then continue with your code.

An example can be found from the Future<> javadoc: http://download.oracle.com/javase/6/docs/api/java/util/concurrent/Future.html

Also see StackOverflow question/answer How to return object from Callable()

浅听莫相离 2024-11-10 09:07:03

想一想:
Android 应用程序的主线程是管理 UI 的线程,因此如果您想等到方法 f() 完成,屏幕将冻结。您可能会认为一个好的解决方案是生成一个新线程并调用其中的方法 f() 并使用可调用或 future 来等待 f()。错误的。线程创建下面的代码将执行,因此您也会遇到同样的问题。
那么如何解决这个问题呢?简单的。重新设计您的应用程序并使用侦听器(也称为回调)。

编辑:侦听器或回调只是 A 类实现的一个或多个方法,并将该实现传递给 B 类来执行它。 B类不知道自己在执行什么,他只是执行一个方法。

示例:

public class A{
    public A (){
        B b = new B (new B.Listener (){
            @Override
            void onResult (String result){
                //result is "Core dumped!"
            }
        });
        b.aMethod ();
    }
}

public class B{
    private final Listener listener;

    public static interface Listener{
        void onResult (String result);
    }

    public B (Listener listener){
        if (listener == null) throw new IllegalArgumentException ("The \"listener\" parameter cannot be null.");
        this.listener = listener;
    }

    public void aMethod (){
        //Do something interesant
        //...
        String error = "Core dumped!"

        //Call the listener
        listener.onResult (error);
    }
}

在您的情况下,您将看到类似的内容:

public class YourClass{
    public void aMethod (){
        FaceBookClass fb = new FaceBookClass ();
        fb.setListenerToF (new FaceBookClass.FListener (){
            @Override
            void theCallback (Result aResult){
                //Do something with result
            }
        });
        fb.f ();

    }
}

public class FaceBookClass{
    public static interface FListener{
        void theCallback (Result aResult);
    }

    public void f (){
        ...
    }

    public void setListenerToF (FListener listener){
        ...
    }
}

Think about this:
The main thread of an android app is the thread that manages the UI, so if you want to wait until the method f() finishes, the screen will freeze. You probably will think that a good solution is to spawn a new thread and call the method f() inside it and use a callable or future to wait f(). Wrong. The code below the thread creation will execute so you will have the same problem.
Then how can you solve this? Simple. Redesign your application and use a listener, a.k.a. callback.

EDIT: A listener or callback is just a method (or methods) that a class A implement and passes this implementation to a class B to execute it. Class B doesn't know what he is executing, he just executes a method.

Example:

public class A{
    public A (){
        B b = new B (new B.Listener (){
            @Override
            void onResult (String result){
                //result is "Core dumped!"
            }
        });
        b.aMethod ();
    }
}

public class B{
    private final Listener listener;

    public static interface Listener{
        void onResult (String result);
    }

    public B (Listener listener){
        if (listener == null) throw new IllegalArgumentException ("The \"listener\" parameter cannot be null.");
        this.listener = listener;
    }

    public void aMethod (){
        //Do something interesant
        //...
        String error = "Core dumped!"

        //Call the listener
        listener.onResult (error);
    }
}

In your case you will have something similar to this:

public class YourClass{
    public void aMethod (){
        FaceBookClass fb = new FaceBookClass ();
        fb.setListenerToF (new FaceBookClass.FListener (){
            @Override
            void theCallback (Result aResult){
                //Do something with result
            }
        });
        fb.f ();

    }
}

public class FaceBookClass{
    public static interface FListener{
        void theCallback (Result aResult);
    }

    public void f (){
        ...
    }

    public void setListenerToF (FListener listener){
        ...
    }
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文