我正在学习有关如何使用 json Web 服务的教程。
但是我有两个疑问,请你帮助我理解。
我正在通过此链接学习 http://codeoncloud.blogspot.in/2013/05/blackberry-java-json-tutorial.html
这是一个通过线程扩展的类
public class ConnectJson extends Thread {
private String url;
public String response;
private String myinterface = ";interface=wifi";
public void run() {
HttpConnection conn = null;
InputStream in = null;
int code;
try {
conn = (HttpConnection) Connector.open(this.url + this.myinterface, Connector.READ);
conn.setRequestMethod(HttpConnection.GET);
code = conn.getResponseCode();
if (code == HttpConnection.HTTP_OK) {
in = conn.openInputStream();
ByteArrayOutputStream out = new ByteArrayOutputStream();
byte[] buffer = new byte[in.available()];
int len = 0;
while (-1 != (len = in.read(buffer))) {
out.write(buffer);
}
out.flush();
this.response = new String(out.toByteArray());
if (out != null){
out.close();
}
if (in != null){
in.close();
}
if (conn != null){
conn.close();
}
}
} catch (Exception e) {
Dialog.inform(e.toString());
}
}
public String jsonResult(String url){
this.url = url;
this.start();
this.run();
return response;
}
}
它正在创建该类的一个对象并调用该类的方法。在该方法中它调用 start 以及 run 方法,为什么?
this.start();
this.run();?
最佳答案
In that method it call start as well as run method why ?
你必须询问代码的作者;查看该类的代码,它看起来不正确。这也相当不寻常。
在正常情况下,您不会调用 run
直接地;您启动线程(使用 start
),然后 JVM 负责创建一个新线程并调用 run
就在上面。
您可以调用run
如果您确实希望该代码立即在当前线程上运行,请自行检查,但这很不寻常,并且该类看起来并不像被设计为正确执行此操作。该代码实际上所做的是启动一个新线程(这意味着 run
最终将在该新线程上被调用),但是正如您所观察到的,它也调用 run
直接地。所以run
将运行两次,并且很可能同时运行两次。由于 run
中的代码使用将由两个线程使用的实例变量,但不执行任何操作来协调对这些实例变量的访问...好吧,再次,它看起来不正确。
我认为我不会继续遵循该教程。您可能会找到Concurrency trail Oracle 的 Java 教程中的内容可能会有用。 (线程是其中的一部分。)
关于java - 为什么在java中同时运行和开始调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20824767/