使用System.out.print与println的多线程问题 [英] Multithreading problem using System.out.print vs println

查看:933
本文介绍了使用System.out.print与println的多线程问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下线程,每200ms只打印一个点:

I have the following thread which simply prints a dot every 200ms:

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 the thread with this code (for now):

 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('。'); ,则代码完全按预期工作。 (除了我每次都不想要新行)。

If I use System.out.println('.'); , the code works exactly as expected. (Apart from the fact that I don't want a new line each time).

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

With System.out.print('.');, the code waits for ten seconds, and then shows the output.

System.out.println


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


System.out.print


     Wait 5000ms, Print all dots


发生了什么,我该怎么做才能绕过这种行为?

What is happening, and what can I do to go around this behaviour?

编辑:

我也试过这个:

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

和printDot()而不是 System.out。 print('。');
它仍然不起作用。

and printDot() instead of System.out.print('.'); It still doesn't work.

EDIT2:

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

Interesting. This code works as expected:

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

Solution: The issue was netbeans related. It worked fine when I run it as a jar file from java -jar.

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

This is one of the most frustrating errors I have seen in my life. When I try to run this code with breakpoints in debug mode, everything works correctly.

推荐答案

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

The stdout is line buffered. Use stderr, or flush the PrintStream after each print.

这篇关于使用System.out.print与println的多线程问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆