简体   繁体   English

如何在Java中等待一项任务完成?

[英]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.

相关问题 Java如何在返回控制之前等待任务完成 - Java How to wait for task to finish before returning control Java-如何在继续执行之前等待实例完成 - Java - How to wait for an instance to finish before proceeding 如何等待ExecutorService中正在运行的线程之一完成以分配其他任务 - How to wait for one of the running threads in ExecutorService to finish to assign another task 等待任务完成,然后终止ScheduledThreadPoolExecutor - Wait for task to finish before terminating in ScheduledThreadPoolExecutor Java等待swing.timer任务完成,然后再执行下一个任务 - java wait for swing.timer task to finish before executing the next task 如何在BlockingQueue Java中优雅地等待作业任务完成 - How to gracefully wait to job task finish in BlockingQueue java 如何在Java / Android中另一个线程启动之前等待线程完成? - How to wait for a thread to finish before another thread starts in Java/Android? 如何在Java中启动更多线程之前等待线程完成 - How to wait for a thread to finish before starting more in Java 如何使Java等待方法完成才能继续? - How do I make Java wait for a method to finish before continuing? 如何在java中打开文件之前等待windows进程完成 - How to Wait for windows process to finish before opening file in java
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM