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
It seems to have nothing to do with caching. The source code of println is like this:
public void println(String x) {
synchronized (this) {
print(x);
newLine();
}
}
Then the source code of printf:
public PrintStream printf(String format, Object ... args) {
return format(format, args);
}
In format, there is nothing more than simple formatting operations
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;
}
As for your question, you can change the sentence printed in the code to:
System.out.printf("Number is Prime: %d", number);
System.out.print("\r");
That’s it
ringa_lee2017-04-18 10:13:00
Perhaps if you encounter problems, you can use Baidu first. .
http://www.jb51.net/article/4...
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);
Newline is a difference, but the main difference is that printf
expressions can be formatted. For specific format syntax, please refer to java.util.Formatter