java 线程返回,如何从Java中的线程返回值?

In android i am creating thread for url connection.Inside the thread i store the response message in a string which is globally declared.When I access the method method it returns null.

public class Rate_fetch {

String total="";

public String rate(String dt)

{

new Thread(new Runnable(){

public void run(){

try {

URL url = new URL(tally_ipaddr+"/prorate.jsp?plist="+sss.toString().trim());

HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();

InputStream in = new BufferedInputStream(urlConnection.getInputStream());

BufferedReader r = new BufferedReader(new InputStreamReader(in));

String x = "";

String total = "";

x = r.readLine();

int i=0;

while(x.length()>1)

{

total=total+x.toString().trim();

i++;

x = r.readLine();

}

}

catch(Exception e){

return e.toString();

}

}

}).start();

return total;

}

When i call the method it returns null.

Rate_fetch rf=new Rate_fetch();

String amt= rf.rate(prodList);

解决方案

It you really want to use Thread only, try this

public class Rate_fetch {

String total = "";

boolean b = true;

public String rate(String dt) {

StringBuilder sb = new StringBuilder();

new Thread(new Runnable() {

public void run() {

try {

URL url = new URL(tally_ipaddr + "/prorate.jsp?plist="

+ sss.toString().trim());

HttpURLConnection urlConnection = (HttpURLConnection) url

.openConnection();

InputStream in = new BufferedInputStream(urlConnection

.getInputStream());

BufferedReader r = new BufferedReader(

new InputStreamReader(in));

StringBuilder sb = new StringBuilder();

String s;

while (true) {

s = r.readLine();

if (s == null || s.length() == 0)

break;

sb.append(s);

}

b = true;

} catch (Exception e) {

b = true;

}

}

}).start();

while (b) {

}

total = sb.toString();

return sb.toString();

}

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值