Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
74 views
in Technique[技术] by (71.8m points)

java - How to return a value from Infinite Loop?


I have a doubt which may be very trivial for many out there.
I am unable to understand how to return a value from infinite running Loop?(if possible)

I have gone through various sources in the internet where they have all advised to go with MultiThreading.


But sadly I am unable to grasp the idea how can Threading be helpful in this case.
Here is my simulated feature I wish to implement :-
void processReturnedValue(){
    for(;;){
        String currentTime = retrieveCurrentTime(); 
        doSomethingWithReturenedValue(currentTime);
        delay(15000); // function to incur delay for 15 Seconds
   }
}

String retrieveCurrentTime(){
     for(;;){
         return currentDateTime.getDayOfYear()+ "_" + currentDateTime.getHour() + "_" +    currentDateTime.getMinute() + "_" + currentDateTime.getSecond();
     delay(15000); // function to incur delay for 15 Seconds
   }
}

I shall be highly obliged if someone can throw some light regarding my doubt.
If possible kindly provide a small working simulated example with respect to mine.
Thanking you in anticipation.

question from:https://stackoverflow.com/questions/65939400/how-to-return-a-value-from-infinite-loop

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Instead of returning, assign the value to a shared variable:

private final AtomicReference<String> currentTime = new AtomicReference<>();

// Thread 1:
void processReturnedValue() {
    for(;;) {
        doSomethingWithReturenedValue(currentTime.get());
        delay(15000); // function to incur delay for 15 Seconds
   }
}

// Thread 2:
String retrieveCurrentTime() {
    for(;;) {
        currentTime.set(currentDateTime.getDayOfYear()+ "_" + currentDateTime.getHour() + "_" +    currentDateTime.getMinute() + "_" + currentDateTime.getSecond());
        delay(15000); // function to incur delay for 15 Seconds
    }
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...