如何从线程返回字符串或从线程中获取字符串?

时间:2015-07-05 14:41:29

标签: java android multithreading java-threads

我需要从一个Thread获取一个String值,但我不能得到它!全局变量不起作用!你能帮帮我吗?

这是我的代码。我需要使用dataString

public class Deserializable {

public void execute() {

    new Thread() {

        public void run() {
            String surl = "http://myaddressxxxxx";
            HttpURLConnection urlConnection = null;
            URL url = null;
            try {
                url = new URL(surl);

                urlConnection = (HttpURLConnection) url.openConnection();
                InputStream in = new BufferedInputStream(
                        urlConnection.getInputStream());
                int b = in.read();
                List<Byte> bytes = new LinkedList<Byte>();
                while (b != -1) {
                    bytes.add((byte) b);
                    b = in.read();
                }
                byte[] array = new byte[bytes.size()];
                for (int i = 0; i < bytes.size(); i++) {
                    array[i] = bytes.get(i).byteValue();
                }

                // I need return this String.
                String dataString = new String(array);

            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                urlConnection.disconnect();
            }
        }
    }.start();

}

1 个答案:

答案 0 :(得分:0)

Thread可以扩展为包含字段,例如dataString。这些字段可以从同一个线程或不同的线程访问,只要它们互相引用即可。

public class ThreadA extends Thread {
   public String dataString;

   public void run(){
      ...
      this.dataString = ...;
      ...
   }
}

public class ThreadB extends Thread {

   private final ThreadA ta;

   public ThreadB(ThreadA ta){
      super();
      this.ta = ta;
   }

   public void run(){
      ...
      do something with ta.dataString...
      ...
   }
}

当然,这会带来并发访问字段dataString的问题。如果您的案例中存在问题,请考虑使用synchronized。有关更多信息,请查看有关并发性的tutorial