java 需要帮助在线程运行方法中返回对象
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2300433/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Need help returning object in thread run method
提问by littleK
I have a Java class that extends Thread, it basically looks like the following:
我有一个扩展的 Java 类Thread,它基本上如下所示:
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() {
...
}
}
I need the run()method to return a ByteArrayOutputStreamor a String. However, because it is in the run()method of the Thread, I cannot set the return type of the method to a ByteArrayOutputStreamor a String.
我需要run()返回 aByteArrayOutputStream或 a的方法String。但是,因为是在 的run()方法中Thread,所以我无法将方法的返回类型设置为 a ByteArrayOutputStream或 a String。
The HttpRequestDispatcherclass is called inside of a class called OAuth.java.
该HttpRequestDispatcher班被称为所谓的OAuth.java类里面。
How can I get around this situation?
我怎样才能解决这种情况?
采纳答案by miku
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.
Make use of a
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.
使用线程外部的数据结构。在您的构造函数中传递对象并在您的 Thread 即将完成时更新它。
使用回调方法。当您的线程完成时,调用回调。
使用
java.util.concurrent.Future(Java >= 1.5):Future 表示异步计算的结果。提供了检查计算是否完成、等待其完成以及检索计算结果的方法。
回答by BalusC
Let it implement Callable<T>instead of Threador Runnable. Here Tmust represent the type of the result. Use ExecutorServiceto execute it. It will return the result in flavor of a Future<V>.
让它实现Callable<T>而不是Threador Runnable。这里T必须代表结果的类型。使用ExecutorService来执行它。它将以 a 的风格返回结果Future<V>。
Here's an SSCCEwith Stringas T, just copy'n'paste'n'run it.
这是一个带有as的SSCCE,只需复制'n'paste'n'run 即可。StringT
package com.stackoverflow.q2300433;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
public class Test {
public static void main(String... args) throws Exception {
ExecutorService executor = Executors.newSingleThreadExecutor();
Future<String> future = executor.submit(new Task());
System.out.println(future.get()); // Prints "result" after 2 secs.
// Or if you have multiple tasks.
// List<Future<String>> futures = executor.invokeAll(Arrays.asList(new Task()));
// for (Future<String> future : futures) {
// System.out.println(future.get());
// }
executor.shutdown(); // Important!
}
}
class Task implements Callable<String> {
public String call() throws Exception {
Thread.sleep(2000);
return "result";
}
}

