栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

你真的理解那句HelloWorld吗?

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

你真的理解那句HelloWorld吗?

你真的理解那句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");

   
    public void println(String x) {
        synchronized (this) { //同步锁,意味着是线程安全的
            print(x);
            newline();
        }
    }

相关API如下:


java.io.PrintStream#println(java.lang.String)

   
    public void print(String s) {
        if (s == null) {
            s = "null";
        }
        write(s);
    }

java.io.PrintStream#write(java.lang.String) 

    private void write(String s) {
        try {
            synchronized (this) {  //同步锁,是线程安全的
                ensureOpen();
                textOut.write(s);
                textOut.flushBuffer();
                charOut.flushBuffer();
                if (autoFlush && (s.indexOf('n') >= 0))
                    out.flush();
            }
        }
        catch (InterruptedIOException x) {
            Thread.currentThread().interrupt();
        }
        catch (IOException x) {
            trouble = true;
        }
    } 

java.io.PrintStream#newline

    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。

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/603141.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号