关于Java的内部类 ?

上面那句

"TimePrinter类在beep参数值消失之前必须将beep字段复制为start方法的 局部变量" 。

和 下面的 红线那句 没有明白。

下面画红线的意思是: start方法的beep参数先复制为 start方法的 局部变量,然后实例化TimePrinter对象的时候又从局部变量传给 TimePrinter 的构造器 ??


回答:

  1. 复制为局部变量也没有用啊,当start方法执行完,start方法的形参 和 局部变量 不都要销毁吗 ?

    start方法执行完,局部变量引用listenertimer无效,但JavaDocs-Timer中指出:

    Corresponding to each Timer object is a single background thread that is used to execute all of the timer's tasks, sequentially. Timer tasks should complete quickly. If a timer task takes excessive time to complete, it "hogs" the timer's task execution thread. This can, in turn, delay the execution of subsequent tasks, which may "bunch up" and execute in rapid succession when (and if) the offending task finally completes.

    After the last live reference to a Timer object goes away and all outstanding tasks have completed execution, the timer's task execution thread terminates gracefully (and becomes subject to garbage collection). However, this can take arbitrarily long to occur. By default, the task execution thread does not run as a daemon thread, so it is capable of keeping an application from terminating. If a caller wants to terminate a timer's task execution thread rapidly, the caller should invoke the timer's cancel method.

    Timer是依靠一个后台线程完成任务的,因此这个线程会保留着对本例中timer所指对象的引用,所以这个对象不会被GC销毁。

  2. 下面画红线的意思是: start方法的beep参数先复制为 start方法的 局部变量,然后实例化TimePrinter对象的时候又从局部变量传给 TimePrinter 的构造器 ?

    这个理解正确。意思是编译器在类TalkingClock$TimePrinter中创建了val$beep实例字段,用来保存start方法中的beep变量。start方法中的局部变量beep会被传递给TalkingClock$TimePrinter的构造函数,用来初始化它的val$beep字段。

以上是 关于Java的内部类 ? 的全部内容, 来源链接: utcz.com/p/944907.html

回到顶部