Im trying to print out some text char by char with some delay, the problem is that it waits and waits and then prints the whole sentence out. It's like it's printing char by char to a string and then printing that string out once its finished:
public static void printWithDelay(String data, TimeUnit unit, long delay)
throws InterruptedException {
for (char ch : data.toCharArray()) {
System.out.print(ch);
unit.sleep(delay);
}
}
please help (:
What values are you running this with? If you are using too small of a sleep value, since you are printing everything on one line, it may seem like it is writing all at once.
Try running it with these values to exaggerate the sleep time. You could also try using a
System.out.println
instead ofSystem.out.print
to show you that it is in fact printing one at a time.You may find calling
flush()
will work but there is no guarantee.See flush()
Why don't you use
Thread.sleep()
?See Pausing Execution with sleep
And How to properly use thread sleep