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()除了换行和格式化的差异之外,是不是在缓存方面还存在差异?
天蓬老师2017-04-18 10:13:00
貌似跟緩存沒啥關係,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");
就可以了
PHPz2017-04-18 10:13:00
Integer number = 55;
System.out.printf("Number " + number + " is Prime\n");
System.out.printf("Number %s is Prime", number);
換行是一個區別,但是最主要的區別是printf
可以格式化表達式,具體格式語法可參考java.util.Formatter