Java printf() 和 println() 的区别是什么?
ringa_lee
ringa_lee 2017-04-18 10:11:00
0
3
620

1.在学习Java7 concurrency cookbook 的第一章节时,发现《Interrupting a thread》这个部分的代码没有达到预期的效果:控制台并没有像书上所描述的那样输出内容。再把其使用的printf()函数换成println()之后;程序得到预期的效果。
2.代码如下:

package lee.twowater.java7.chapterThree; public class PrimeGenerator extends Thread { @Override public void run() { long number = 1L; while (true) { if (isPrime(number)) { System.out.printf("Number "+ number +" is Prime"); } if (isInterrupted()) { System.out.printf("The Prime Generator has been Interrupted"); return; } number++; } } private boolean isPrime(long number) { if (number <= 2) { return true; } for (long i = 2; i < number; i++) { if ((number % i) == 0) { return false; } } return true; } } package lee.twowater.java7.chapterThree; public class Main { public static void main(String[] args) { Thread task = new PrimeGenerator(); task.start(); try { Thread.sleep(5000); } catch (InterruptedException e) { e.printStackTrace(); } task.interrupt(); } }

3.我猜想println()和printf()除了换行和格式化的差异之外,是不是在缓存方面还存在差异?

ringa_lee
ringa_lee

ringa_lee

모든 응답 (3)
Peter_Zhu

貌似跟缓存没啥关系,println的源码是这样的:

public void println(String x) { synchronized (this) { print(x); newLine(); } }

然后是printf的源码:

public PrintStream printf(String format, Object ... args) { return format(format, args); }

在format里面就是单纯的格式化操作没啥了

public PrintStream format(String format, Object ... args) { try { synchronized (this) { ensureOpen(); if ((formatter == null) || (formatter.locale() != Locale.getDefault())) formatter = new Formatter((Appendable) this); formatter.format(Locale.getDefault(), format, args); } } catch (InterruptedIOException x) { Thread.currentThread().interrupt(); } catch (IOException x) { trouble = true; } return this; }

至于你的那个问题你可以把代码里打印输出的那一句改为:

System.out.printf("Number is Prime: %d", number); System.out.print("\r");

就可以了

    左手右手慢动作

    或许碰到问题可以先百度。。
    http://www.jb51.net/article/4...

      PHPzhong
      Integer number = 55; System.out.printf("Number " + number + " is Prime\n"); System.out.printf("Number %s is Prime", number);

      换行是一个区别,但是最主要的区别是printf可以格式化表达式,具体格式语法可参考java.util.Formatter

        최신 다운로드
        더>
        웹 효과
        웹사이트 소스 코드
        웹사이트 자료
        프론트엔드 템플릿
        회사 소개 부인 성명 Sitemap
        PHP 중국어 웹사이트:공공복지 온라인 PHP 교육,PHP 학습자의 빠른 성장을 도와주세요!