iteye_6382 2012-07-27 11:16
浏览 311
已采纳

关于System.in的分析

最近在看《JAVA编程思想》,其中System.in迷惑了我。
首先看下System的源码(jdk1.6)
[code="java"]
public final static InputStream in = nullInputStream();

private static InputStream nullInputStream() throws NullPointerException {
if (currentTimeMillis() > 0) {
return null;
}
throw new NullPointerException();
}
[/code]

疑问1: 通过源码可以看到 System.in是System类的一个静态属性,其为InputStream,初始时通过nullInputStream()方法返回,但是return null?

疑问2: 写了一个测试类,通过语句System.out.println(System.in); 打印出结果为:java.io.BufferedInputStream@1fb8ee3,说明System.in是BufferedInputStream类型,如何实现的?

疑问3: 如果线程执行到System.in.read();时,未在console输入内容,线程将挂起,直到console有输入内容。如何实现的?

  • 写回答

3条回答 默认 最新

  • weixin_42608382 2012-07-27 13:17
    关注

    [code="java"]
    /**

    • The following two methods exist because in, out, and err must be
    • initialized to null. The compiler, however, cannot be permitted to
      • inline access to them, since they are later set to more sensible values
    • by initializeSystemClass(). */ private static InputStream nullInputStream() throws NullPointerException { if (currentTimeMillis() > 0) return null; throw new NullPointerException(); } [/code]

    注意上面的注释:initializeSystemClass().
    [code="java"]
    private static void initializeSystemClass() {
    props = new Properties();
    initProperties(props);
    sun.misc.Version.init();
    FileInputStream fdIn = new FileInputStream(FileDescriptor.in);
    FileOutputStream fdOut = new FileOutputStream(FileDescriptor.out);
    FileOutputStream fdErr = new FileOutputStream(FileDescriptor.err);
    setIn0(new BufferedInputStream(fdIn));
    setOut0(new PrintStream(new BufferedOutputStream(fdOut, 128), true));
    setErr0(new PrintStream(new BufferedOutputStream(fdErr, 128), true));
    [/code]
    这里的in 不就是个buffer类型的了。咋都不看方法的注释呢!~~

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 求差集那个函数有问题,有无佬可以解决
  • ¥15 【提问】基于Invest的水源涵养
  • ¥20 微信网友居然可以通过vx号找到我绑的手机号
  • ¥15 寻一个支付宝扫码远程授权登录的软件助手app
  • ¥15 解riccati方程组
  • ¥15 display:none;样式在嵌套结构中的已设置了display样式的元素上不起作用?
  • ¥15 使用rabbitMQ 消息队列作为url源进行多线程爬取时,总有几个url没有处理的问题。
  • ¥15 Ubuntu在安装序列比对软件STAR时出现报错如何解决
  • ¥50 树莓派安卓APK系统签名
  • ¥65 汇编语言除法溢出问题