你真的理解那句HelloWorld吗?
1.首先看这个main入口函数
public static void main(String sfd[]) {
System.out.println("Hello World");
}
public static void main(String[] sfd) {
System.out.println("Hello World");
}
这两种写法语法检测器与编译器都能正常通过,不影响执行结果。但为了避免语义歧义,一般建议这种常规的写法:
public static void main(String[] args) {
System.out.println("Hello World");
}
2.查看一下这个println函数
java.io.PrintStream#println(java.lang.String)
//System.out.println("Hello World");
/**
* Prints a String and then terminate the line. This method behaves as
* though it invokes <code>{@link #print(String)}</code> and then
* <code>{@link #println()}</code>.
*
* @param x The <code>String</code> to be printed.
*/
public void println(String x) {
synchronized (this) { //同步锁,意味着是线程安全的
print(x);
newLine();
}
}
相关API如下:
/**
* Prints a string. If the argument is <code>null</code> then the string
* <code>"null"</code> is printed. Otherwise, the string's characters are
* converted into bytes according to the platform's default character
* encoding, and these bytes are written in exactly the manner of the
* <code>{@link #write(int)}</code> method.
*
* @param s The <code>String</code> to be printed
*/
public void print(String s) {
if (s == null) {
s = "null";
}
write(s);
}
private void newLine() {
try {
synchronized (this) { //同步锁,是线程安全的
ensureOpen();
textOut.newLine();
textOut.flushBuffer();
charOut.flushBuffer();
if (autoFlush)
out.flush();
}
}
catch (InterruptedIOException x) {
Thread.currentThread().interrupt();
}
catch (IOException x) {
trouble = true;
}
}
一层一层看API函数源码,可得知这句简单的"HelloWorld"的输出是线程安全的。
记录与总结,2021年 11月 25日 星期四 01:03:24 CST。