我有一个班级:
class RenderView implements Runnable {
Thread renderThread;
public void run() {
while(!Thread.currentThread().isInterrupted()) {
//does some work
}
}
//At some point in executed code, inside RenderView class (i'm sure it's executed)
renderThread = new Thread (this);
//When activity is closed (also, i'm sure this part is executed)
renderThread.interrupt();
并且renderThread确实停止了(至少run()方法退出)。
但由于某些原因,我退出活动后仍然在我的代码中引用了renderView。这导致了巨大的内存泄漏。
hprof转储告诉我: java.lang.Thread(这个在GC Root中) 有参考 target(mypackage.RenderView)
我不知道为什么这个Thread类会保留对我的Thread的引用,即使我已经完成了Thread!任何想法?
编辑:在活动B中引用了renderView。因此,当我退出活动时,仍然无法访问对renderThread的引用。但我仍然尝试设置renderThread = null:不起作用。正如我能够通过MAT分析器找到的那样,唯一让renderView不被垃圾收集的东西就是来自java.lang.Thread的这个weir引用。
答案 0 :(得分:2)
为什么不使用AsyncTask或runOnUIThread()?
我从未见过你需要做什么。也许只有一个,但只是使用AsyncTask或runOnUIThread。不要重新发明轮子。
答案 1 :(得分:1)
使用
释放您的线程实例renderThread = null;
线程实例与任何其他实例一样,是一个对象。即使它已经完成运行,你也会保留它的引用,直到你释放它为止。
答案 2 :(得分:0)
您是否尝试取消renderThread
?
答案 3 :(得分:0)
实际上,renderThread.interrupt可能无法停止该线程,它只是设置一个标志和Singnals JVM它可以被中断。这就是为什么你的线程仍在运行。最佳实践是优雅地从run方法退出只是在while循环中设置一个标志。
while(isRunning){
}
// at some point, say
isRunning = false;
Android UI设计的最佳做法可以从以下链接获得。