0

我需要从线程中获取字符串值,但我不明白!全局变量不起作用!你能帮我吗?

这是我的代码。我需要使用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();

}
4

1 回答 1

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...
      ...
   }
}

当然,这带来了并发访问字段的问题dataStringsynchronized如果这对您来说是个问题,请考虑使用。查看有关并发的本教程以获取更多信息。

于 2015-07-05T15:07:48.097 回答