计时器对象不是由垃圾收集器收集吗?

发布于 2025-02-05 02:41:21 字数 1135 浏览 1 评论 0原文

我尝试弄清以下代码:

    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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

绳情 2025-02-12 02:41:21

计时器的线程具有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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文