将 null 设置为 Thread 以防止 onDestroy 中的内存泄漏 Android

Set null to Thread to prevent memory leak in onDestroy Android

我正在使用 Thread 进行一些异步操作。现在我主要有 3 个线程,例如:

private lateinit var horse1Thread: Thread
private lateinit var horse2Thread: Thread
private lateinit var timerThread: Thread

在 activity 的 onDestroy() 中调用 stop() 会导致 UnsupportedOperationException,我想将这些值设置为 null 以允许 GC 收集并防止内存泄露。由于我的字段是 non-null 类型,因此我无法将它们设置为 null。那么 this 是我唯一的选择吗?或者 kotlin 是否提供了一种方法来释放这些字段占用的内存?我可以将它们的类型设置为可为空,但我觉得这违背了目的?

我认为您不必关心将这些字段设置为空。 Thread 应该完成他的工作,然后 Thread 将处于 TERMINATED 状态。稍后垃圾收集器将在没有你的情况下清理它。您应该只关心这些线程的状态,并以这种方式在这些线程中构建逻辑,使它们在没有任何无限循环的情况下完成它们的工作。

所以基本上你在线程内的长操作中需要一些触发器,通过点击按钮这个触发器应该跳过(或取消)你在线程内的长操作。之后该线程将自己转到 TERMINATED 线程。

将它们设置为 null 没有任何作用,因为线程仍然 运行 并且虚拟机将在它们运行时跟踪它们。

您需要做的是引入一种方法来发出线程不应再继续的信号。这通常是通过检查循环中的 Thread.isInterrupted() 并在为真时结束循环来完成的。然后你只需要在你的 onDestroy 方法中调用 Thread.interrupt() 来清理线程。

实际上,甚至还有关于 Thread.stop() 为什么不应该使用它的描述:

https://docs.oracle.com/javase/7/docs/api/java/lang/Thread.html#stop()

This method is inherently unsafe. Stopping a thread with Thread.stop causes it to unlock all of the monitors that it has locked (as a natural consequence of the unchecked ThreadDeath exception propagating up the stack). If any of the objects previously protected by these monitors were in an inconsistent state, the damaged objects become visible to other threads, potentially resulting in arbitrary behavior. Many uses of stop should be replaced by code that simply modifies some variable to indicate that the target thread should stop running. The target thread should check this variable regularly, and return from its run method in an orderly fashion if the variable indicates that it is to stop running.