java - 需要帮助在线程运行方法中返回对象

标签 java multithreading methods return

我有一个扩展 Thread 的 Java 类,它基本上如下所示:

public class HttpRequestDispatcher extends Thread {
    private String url;
    private String method; // GET or POST
    private byte[] postData;

    public HttpRequestDispatcher(String url, String method, byte[] postData) {
        this.url = url;
        this.method = method;
        this.postData = postData;
    }

    public HttpRequestDispatcher(String url, String method) {
        this.url = url;
        this.method = method;
    }

    public void run() {
        ...
    }
}

我需要 run() 方法来返回 ByteArrayOutputStreamString。但是,因为它在 Threadrun() 方法中,所以我无法将方法的返回类型设置为 ByteArrayOutputStream字符串

HttpRequestDispatcher 类在名为 OAuth.java 的类中调用。

我该如何解决这种情况?

最佳答案

这个问题有几种解决方法:

  • 使用线程外部的数据结构。在您的线程即将完成时,在您的构造函数中传递对象并更新它。

  • 使用回调方法。当您的线程完成时,调用回调。

  • 利用 java.util.concurrent.Future (Java >= 1.5):

    A Future represents the result of an asynchronous computation. Methods are provided to check if the computation is complete, to wait for its completion, and to retrieve the result of the computation.

关于java - 需要帮助在线程运行方法中返回对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2300433/

相关文章:

javascript - JS : why do i need brackets to call a method on number?

c# - 在不锁定 GUI 的情况下暂停方法的执行。 C#

multithreading - Scala future 执行

javascript - 使用 SetInterval() 调用 Javascript 对象方法

java - 带空格的路径

java - PrintStream 无法正确打印 unicode 字符 (UTF-16)

java - 自定义 Jackson ObjectMapper 以读取自定义注释并屏蔽带注释的字段

java - 显示抄袭结果

java - 想要在线程的 run() 函数的 Main 函数中使用一个 int 数组

java - 多线程应用程序中的静态计数器线程是否安全?