当我在Thread对象上调用run()时,为什么Java程序会泄漏内存? [英] Why is my Java program leaking memory when I call run() on a Thread object?

查看:96
本文介绍了当我在Thread对象上调用run()时,为什么Java程序会泄漏内存?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

(Jeopardy式的问题,我希望当我遇到这个问题时,答案已经在线)

(Jeopardy-style question, I wish the answer had been online when I had this issue)

使用Java 1.4,我有一种方法希望在某些时候作为线程运行,而在其他时候则不想.因此,我将其声明为Thread的子类,然后根据需要将其命名为start()或run().

Using Java 1.4, I have a method that I want to run as a thread some of the time, but not at others. So I declared it as a subclass of Thread, then either called start() or run() depending on what I needed.

但是我发现我的程序会随着时间的流逝而泄漏内存.我在做什么错了?

But I found that my program would leak memory over time. What am I doing wrong?

推荐答案

这是Java 1.4中的一个已知错误: http://bugs.sun.com/bugdatabase/view_bug .do; jsessionid = 5869e03fee226ffffffffcc40d4fa881a86e3:WuuT?bug_id = 4533087

This is a known bug in Java 1.4: http://bugs.sun.com/bugdatabase/view_bug.do;jsessionid=5869e03fee226ffffffffc40d4fa881a86e3:WuuT?bug_id=4533087

它已在Java 1.5中修复,但Sun并不打算在1.4中修复它.

It's fixed in Java 1.5 but Sun doesn't intend to fix it in 1.4.

问题在于,在构造时,会将Thread添加到内部线程表中的引用列表中.直到它的start()方法完成后,它才会从该列表中删除.只要该引用存在,就不会收集垃圾.

The issue is that, at construction time, a Thread is added to a list of references in an internal thread table. It won't get removed from that list until its start() method has completed. As long as that reference is there, it won't get garbage collected.

因此,除非您肯定要调用其start()方法,否则请不要创建线程. Thread对象的run()方法不应直接调用.

So, never create a thread unless you're definitely going to call its start() method. A Thread object's run() method should not be called directly.

一种更好的编码方法是实现Runnable接口,而不是子类.当您不需要线程时,请致电

A better way to code it is to implement the Runnable interface rather than subclass Thread. When you don't need a thread, call

myRunnable.run();

当您确实需要线程时:

Thread myThread = new Thread(myRunnable);
myThread.start();

这篇关于当我在Thread对象上调用run()时,为什么Java程序会泄漏内存?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆