[英]My method is returning only the last value that was gotten from the while loop
[英]Returning the value from the loop
我正在使用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'
}
如果您需要處理與循環並發進行,那么您將需要使用多個線程,問題會變得更加復雜。
那到底是什么意思?
如果您想停留在同一線程中,只需調用一個函數(處理收到的一條消息,然后閱讀下一條)。
如果您需要並發(無論是否重新處理郵件,都必須閱讀),請使用生產者/使用者模式。 創建一個線程
創建至少一個mor線程
心連心
馬里奧
使您的返回值更具可見性。 因此,您將獲得其價值
聽起來您正在引用yield功能,該功能允許您的函數返回多個值。 據我所知,Java尚不支持開箱即用,但是有一些項目可以實現此功能。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.