我有一个扩展 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()
方法来返回 ByteArrayOutputStream
或 String
。但是,因为它在 Thread
的 run()
方法中,所以我无法将方法的返回类型设置为 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/