简体   繁体   中英

Add delay to a for-loop without using Thread.sleep — Nevermind it's a bad idea

I have this code which takes in a String ...

//Takes in string from whatever it is, in this case a JOptionPane
String input = JOptionPane.showInputDialog("Input string");
//if there is a string 
if (!(input == null)) {
    //splits the string into smaller strings of 100 characters for loop that prints the strings  
    int count = input.length() / 100 + 1;
    for (int i = 0; i < count; i++) {
        System.out.println(input.substring(i * 100, (i + 1) * 100 >= input.length() ? input.length() : (i + 1) * 100));
    }
}

..and I want to add a delay to the string so that it doesn't all print the strings in succession at once but instead prints one string every second without using a Thread.sleep(1000) .

Does anyone have an idea as to how I could do this?

You can try to schedule a task using ScheduledExecutorService to print the next characters with an initial delay. Then reschedule with the next characters to print until you finish. ScheduledExecutorService runs on a different thread so if you want to wait until all the String is printed you will have to use something like a CompletableFuture to indicate when all is done. Also make sure the thread has stopped when the printing is complete so it wont run indefinitely.

What you're looking for is simply not intuitive* without the use of Thread.sleep , because that is far and away the simplest approach to adding a delay in your code.

To rephrase it: any solution you'd want to come up with that avoids the direct Thread.sleep would involve adding the strings to some buffer or waiting area, polling that buffer every second, and printing it out to string, until the buffer is depleted. Effectively this is accomplished with worker threads and queues, but if the intent is to only ever print the strings out, the simplest effect would be to use Thread.sleep(1000) .

*: I say "intuitive" since there may be a way to do it, but any alternative workarounds would likely use Thread.sleep with several layers of indirection.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM