我有以下线程,它每 200 毫秒打印一个点:
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;
}
}
}
我用以下代码启动线程(目前):
System.out.println("Working.");
Progress.start();
try {
Thread.sleep(10000); //To be replaced with code that does work.
} catch (InterruptedException ex) {}
Progress.stop();
真正奇怪的是:
如果我使用System.out.println('.');
,代码完全按照预期工作。 (除了我不想每次都换行这一事实)。
With System.out.print('.');
,代码等待十秒钟,然后显示输出。
System.out.println
:
Print dot, wait 200ms, print dot, wait 200ms etc...
System.out.print
:
Wait 5000ms, Print all dots
发生了什么事,我可以采取什么措施来解决这种行为?
EDIT:
我也尝试过这个:
private static synchronized void printDot()
{
System.err.print('.');
}
和 printDot() 而不是System.out.print('.');
它仍然不起作用。
EDIT2:
有趣的。此代码按预期工作:
System.out.print('.');
System.out.flush(); //Makes no difference with or without
System.out.println();
这不会:
System.err.print('.');
System.err.flush();
System.out.print('.');
System.out.flush();
解决方案:该问题与 netbeans 相关。当我从 java -jar 将其作为 jar 文件运行时,它工作得很好。
这是我一生中见过的最令人沮丧的错误之一。当我尝试在调试模式下使用断点运行此代码时,一切正常。