0

I need to get a String value from a Thread, but I don't get it! Global variables don't work! Can you help me please?

This is my code. I need to use the 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();

}
deezy
  • 1,480
  • 1
  • 11
  • 22

1 Answers1

0

Thread can be extended to have fields, like for your dataString. These fields can be accessed from the same thread or from a different one, as long they have references to each other.

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

Of course, this poses the problem of concurrent access to the field dataString. Consider using synchronized, if this is an issue in your case. Have a look at this tutorial on concurrency for more information.

Eric Leibenguth
  • 4,167
  • 3
  • 24
  • 51