需要帮助在线程运行方法中返回对象 [英] Need help returning object in thread run method

查看:17
本文介绍了需要帮助在线程运行方法中返回对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have a Java class that extends Thread, it basically looks like the following:

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() 方法来返回一个 ByteArrayOutputStream 或一个 String.但是,因为它在Threadrun()方法中,所以我无法将方法的返回类型设置为ByteArrayOutputStream字符串.

I need the run() method to return a ByteArrayOutputStream or a String. However, because it is in the run() method of the Thread, I cannot set the return type of the method to a ByteArrayOutputStream or a String.

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

The HttpRequestDispatcher class is called inside of a class called OAuth.java.

我该如何解决这种情况?

How can I get around this situation?

推荐答案

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

There are several solutions to this problem:

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

  • Use an data structure external to the Thread. Pass the object in your constructor and update it, when your Thread is about to finish.

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

Use a callback method. When your Thread finishes, call the callback.

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

Make use of a java.util.concurrent.Future (Java >= 1.5):

Future 表示异步计算的结果.提供了检查计算是否完成、等待其完成以及检索计算结果的方法.

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.

这篇关于需要帮助在线程运行方法中返回对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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