gpt4 book ai didi

Java 从 Thread 和 Runnable 获取结果

转载 作者:行者123 更新时间:2023-11-30 09:01:53 25 4
gpt4 key购买 nike

在下面的代码中,我无法从 Foo 类的 getValue 获得结果,并且返回 null 但这必须是返回值。结果是正确的,这个函数不能返回那个。例如这是我的课:

public class JsonService {
private JSONObject json = new JSONObject();
public JsonService(final String username, final String password) throws Exception{
json.put("username", username);
json.put("password", password);
}
public class Foo implements Runnable {
private String result;

@Override
public void run() {
HttpClient client = new DefaultHttpClient();
HttpConnectionParams.setConnectionTimeout(client.getParams(), 10000);
HttpResponse response;

try {
HttpPost post = new HttpPost("http://www.example.com/json_android.php");
StringEntity se = new StringEntity( json.toString());
se.setContentType(new BasicHeader(HTTP.CONTENT_TYPE, "application/json"));
post.setEntity(se);
response = client.execute(post);
if(response!=null){
InputStream stream = response.getEntity().getContent();
result = convertToString(stream);

/*
I can Log result with below line
*/
Log.e("response is: ", result);

/*
result is {"username = ":"Hello"}
*/
}
} catch(Exception e) {
e.printStackTrace();
Log.e("Error", String.valueOf(e));
}
}

public String getValue() {
/*
return in this fucntion not working
*/
return result;
}
}
public String request() throws ExecutionException, InterruptedException {
Foo foo = new Foo();
new Thread(foo).start();
return foo.getValue();
}

如何从 Foo 正确获取结果并从 reauest() 返回结果?请帮我。谢谢

最佳答案

使用 FutureTask并实现 Callable .

public class Foo implements Callable<String> {

@Override
public String call() {
String result = null;
HttpClient client = new DefaultHttpClient();
HttpConnectionParams.setConnectionTimeout(client.getParams(), 10000);
HttpResponse response;

try {
HttpPost post = new HttpPost("http://www.example.com/json_android.php");
StringEntity se = new StringEntity( json.toString());
se.setContentType(new BasicHeader(HTTP.CONTENT_TYPE, "application/json"));
post.setEntity(se);
response = client.execute(post);
if(response!=null){
InputStream stream = response.getEntity().getContent();
result = convertToString(stream);

/*
I can Log result with below line
*/
Log.e("response is: ", result);

/*
result is {"username = ":"Hello"}
*/
}

} catch(Exception e) {
e.printStackTrace();
Log.e("Error", String.valueOf(e));
}
return result;
}
}

然后将它与 FutureTask 一起使用

public String request() throws ExecutionException, InterruptedException {
Foo foo = new Foo();
FutureTask<String> fooFuture = new FutureTask<String>(foo);
new Thread(fooFuture).start();
return fooFuture.get();
}

关于Java 从 Thread 和 Runnable 获取结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26192965/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com