I have the following stream, which simply prints a dot every 200 ms:
public class Progress { private static boolean threadCanRun = true; private static Thread progressThread = new Thread(new Runnable() { public void run() { while (threadCanRun) { System.out.print('.'); System.out.flush(); try { progressThread.sleep(200); } catch (InterruptedException ex) {} } } }); public static void stop() { threadCanRun = false; progressThread.interrupt(); } public static void start() { if (!progressThread.isAlive()) { progressThread.start(); } else { threadCanRun = true; } } }
I start a thread with this code (for now):
System.out.println("Working."); Progress.start(); try { Thread.sleep(10000);
Which is really strange:
If I use System.out.println('.');
, the code works exactly as expected. (Besides the fact that I do not want a new line every time).
With System.out.print('.');
the code waits ten seconds and then displays the output.
System.out.println
:
Print dot, wait 200ms, print dot, wait 200ms etc...
System.out.print
:
Wait 5000ms, Print all dots
What happens and what can I do to get around this behavior?
EDIT:
I also tried this:
private static synchronized void printDot() { System.err.print('.'); }
and printDot () instead of System.out.print('.');
This still does not work.
EDIT2:
Interesting. This code works as expected:
System.out.print('.'); System.out.flush(); //Makes no difference with or without System.out.println();
It does not mean:
System.err.print('.'); System.err.flush(); System.out.print('.'); System.out.flush();
Solution: The problem is with netbeans. It worked fine when I run it as a jar file from java -jar.
This is one of the most unpleasant mistakes I've seen in my life. When I try to run this code using breakpoints in debug mode, everything works correctly.