gpt4 book ai didi

java - 从循环中返回值

转载 作者:行者123 更新时间:2023-11-30 11:57:31 25 4
gpt4 key购买 nike

我正在使用 rabbitMQ 进行 POC 并编写一个程序来添加两个数字并获得响应。
我们编写的用于从队列中检索值的代码正在运行无限时间(在 while 循环中)并且一行(在 while 循环中)等待从队列中检索一些数据;在它从队列中得到一些东西之前,它不会进入下一轮 while 循环。
意味着我们正在无限循环中获取值。我想将这个值用于我的下一个处理。


while (true){                       QueueingConsumer.Delivery delivery1;      try      {            delivery = consumer.nextDelivery();//The above line waits until delivery get some value            String result1 = new String(delivery1.getBody());            System.out.println("Result received-"+ result1);       }       catch (InterruptedException ie)       {              continue;       } }  // end while

问题是我无法从 while 循环返回值(我想无限运行它)。
我怎样才能做到这一点,以便循环继续,我也将在循环外获取处理后的数据?

最佳答案

如果“处理结果”是一个快速完成的操作,那么只需内联即可,例如通过调用一个单独的函数来进行实际处理:

void mainLoop()
{
while (true)
{
QueueingConsumer.Delivery delivery1;
try
{
delivery = consumer.nextDelivery();
//The above line waits until delivery get some value
String result1 = new String(delivery1.getBody());
System.out.println("Result received-"+ result1);
processResult(result1);
}
catch (InterruptedException ie)
{
continue;
}
} // end while
}

void processResult(String result)
{
// Do whatever needs to be done with 'result'
}

如果您需要处理与循环同时发生,那么您将需要使用多个线程,问题会变得有点复杂。

关于java - 从循环中返回值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3757725/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com