[英]How do I return a String from a Thread or get a string from a Thread?
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
: 我需要使用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();
}
Thread
can be extended to have fields, like for your dataString
. 可以将Thread
扩展为具有字段,例如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
. 当然,这带来了并发访问字段dataString
。 Consider using synchronized
, if this is an issue in your case. 如果您遇到这种情况,请考虑使用synchronized
。 Have a look at this tutorial on concurrency for more information. 有关更多信息,请参阅本教程 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.