[英]How to wait for one task to finish before in java?
I have a string and I am parsing it and storing it to JsonArray and then iterating over it. 我有一个字符串,我正在解析它并将其存储到JsonArray,然后对其进行迭代。 There is a race condition that my parser isn't completing and the control moves ahead. 有一个竞争条件,我的解析器未完成,控件继续前进。 I want this to complete first then move ahead. 我希望这先完成然后继续。
I tried to wait and notify. 我试图等待并通知。 It isn't working. 它不起作用。
Response res = run(el);
JsonParser parser = new JsonParser();
JsonElement jsonTree = parser.parse(res.body().string());
try {
wait();
} catch(InterruptedException e) {
e.printStackTrace();
}
System.out.println("jsontree : "+ jsonTree);
JsonArray array=jsonTree.getAsJsonArray();
notifyAll();
if(jsonTree.isJsonArray()) {
System.out.println("I am JSONARRAY");
}
for(JsonElement element: array) {
count++;
System.out.println("count "+ count);
}
Right now jsonTree is empty and it looks like this: []
. 现在,jsonTree为空,它看起来像这样: []
。 I want the jsonTree to have objects. 我希望jsonTree具有对象。 Any suggestions? 有什么建议么?
Java by default is executed line by line ie its synchronous in nature by default. 默认情况下,Java是逐行执行的,即默认情况下其本质上是同步的。 It means once your parser will complete then only it will move to next line. 这意味着解析器一旦完成,就只会移动到下一行。 You wont require any asynchronous way to implement it. 您将不需要任何异步方式来实现它。 Just check for correctness of your response obj and parser. 只需检查您的响应obj和解析器的正确性即可。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.