计时器对象不是由垃圾收集器收集吗?
我尝试弄清以下代码:
package com.company;
import java.util.Calendar;
import java.util.Timer;
import java.util.TimerTask;
public class Main {
public static void main(String[] args) {
Timer T = new Timer();
TimerTask Birthday = new TimerTask(){
int i = 5;
@Override
public void run(){
if(i>0){
System.out.println(i);
i--;
}
else{
System.out.println("Happy Birthday John Doe");
T.cancel();
}
}
};
Calendar date = Calendar.getInstance();
date.set(2021, Calendar.OCTOBER, 30,23, 59, 54);
T.scheduleAtFixedRate(Birthday, date.getTime(), 1000);
}
}
我很难理解以下行的工作原理:
t.cancel();
当 main 方法结束时,垃圾收集器是否收集了T(计时器)? 毕竟运行 timertask 类的方法继续在 main 线程后继续运行,因此我假设计时器t 对象是由垃圾收集器收集的,并且在运行行 t.cancel()时应出现运行时间异常。 有人可以向我解释我看到的东西怎么了?
I try to figure the following code:
package com.company;
import java.util.Calendar;
import java.util.Timer;
import java.util.TimerTask;
public class Main {
public static void main(String[] args) {
Timer T = new Timer();
TimerTask Birthday = new TimerTask(){
int i = 5;
@Override
public void run(){
if(i>0){
System.out.println(i);
i--;
}
else{
System.out.println("Happy Birthday John Doe");
T.cancel();
}
}
};
Calendar date = Calendar.getInstance();
date.set(2021, Calendar.OCTOBER, 30,23, 59, 54);
T.scheduleAtFixedRate(Birthday, date.getTime(), 1000);
}
}
I have difficult to understand how the following line works:
T.cancel();
Isn't T (Timer) was collected by garbage collector when the main method ends?
After all the run method of TimerTask class continue to run after main thread was close and therefore i assume that Timer T object was collected by garbage collector and when running the row T.cancel() a run time exception should appear.
Can someone explain me what is wrong with the way i see the things?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
计时器的线程具有
t
实例的引用,因此不会收集垃圾。直到每个实时线程都无法访问对象,就不能收集垃圾。The Timer's thread has a reference to the
T
instance and therefore it will not be garbage collected. An object cannot be garbage collected until it is unreachable to every live thread.