java 线程 system out_java – 使用System.out.print vs println的多线程问题

博客探讨了在Java线程中使用System.out.print('.')与System.out.println('.')的区别。当使用System.out.print时,代码会等待10秒才显示输出,而System.out.println则按预期立即工作。问题与NetBeans相关,通过java -jar运行jar文件时表现正常。解决方案表明此问题与IDE的调试模式有关。
摘要由CSDN通过智能技术生成

我有以下线程,每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;

}

}

}

我用这段代码启动线程(现在):

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:

06002

是System.out.print:

06003

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

编辑:

我也试过这个:

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

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值