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()除了换行和格式化的差异之外,是不是在缓存方面还存在差异?
It seems to have nothing to do with caching. The source code of println is like this:
Then the source code of printf:
In format, there is nothing more than simple formatting operations
As for your question, you can change the sentence printed in the code to:
That’s it
Perhaps if you encounter problems, you can use Baidu first. .
http://www.jb51.net/article/4...
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