java - 使用 System.out.print 与 println 的多线程问题

标签 java multithreading

我有以下线程,它每 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('.'); ,代码将完全按预期工作。 (除了我不想每次都换行的事实)。

使用 System.out.print('.');,代码等待十秒钟,然后显示输出。

System.out.println:

     Print dot, wait 200ms, print dot, wait 200ms etc...

System.out.print:

     Wait 5000ms, Print all dots

发生了什么,我该怎么做才能解决这个问题?

编辑:

我也试过这个:

private static synchronized void printDot()
{
    System.err.print('.');
}

和 printDot() 而不是 System.out.print('.'); 还是不行。

编辑 2:

很有趣。此代码按预期工作:

        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 文件运行时,它工作正常。

这是我一生中见过的最令人沮丧的错误之一。当我尝试在 Debug模式下使用断点运行这段代码时,一切正常。

最佳答案

标准输出是行缓冲的。 使用 stderr,或在每次打印后刷新 PrintStream。

关于java - 使用 System.out.print 与 println 的多线程问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7554499/

相关文章:

java - 一台服务器多个客户端

C# 编译器优化循环?

python - 当 threading.active_count() 返回 1 时,我可以假设我的线程已完成吗?

java - 如何在 Java 中比较字符串?

java - 如何在 SQL Java 中将列表值作为参数传递

java - 如何在快速排序后打印排序数组

java线程与java进程性能下降

java - 请解释 intern() 方法的功能

java - IntelliJ 中的终端无法正常工作 - 但正常的 zsh 终端工作正常

Java JFace 数据绑定(bind) : Update SWT widget from background thread