1

如果我创建一个实现 Runnable 的对象,并用它启动一个线程......

ArrayList<Thread> threadlist = new ArrayList<Thread>();
{
  MergeThread mmt = new MergeThread();
  Thread t = new Thread(mmt);
  threadlist.add(mmt);
  t.start();
}

t.join();
Thread t = threadlist.get(0);

此时 mmt 保证存在,或者如果垃圾收集得到它,它可能已经消失。

我要问的是 Thread 对象在线程结束后是否保留 Runnable 类。

编辑:上面有一个错误应该说 threadlist.add(t);

4

3 回答 3

3

课程的来源Thread

/**
 * This method is called by the system to give a Thread
 * a chance to clean up before it actually exits.
 */
private void exit() {
if (group != null) {
    group.remove(this);
    group = null;
}
/* Aggressively null out all reference fields: see bug 4006245 */
target = null;
/* Speed the release of some of these resources */
    threadLocals = null;
    inheritableThreadLocals = null;
    inheritedAccessControlContext = null;
    blocker = null;
    uncaughtExceptionHandler = null;
}

因此,系统调用Thread#exit()和对target(线程正在运行的可运行对象)的引用被释放。

bugs.sun.com 上还有一个错误报告 #4006245,它指的是清除target参考。

于 2012-06-04T21:54:49.410 回答
2

mmt被添加到,threadList所以只要它threadList本身是可访问的并且仍然持有它,它就不会被垃圾收集,在代码示例的最后一行仍然是这种情况,无论您的第一个t(在中间块中)是否仍然持有对它的引用或不。

于 2012-06-04T21:54:05.607 回答
1

您发布的代码对我来说并不是很清楚。然而,关于

此时 mmt 保证存在,或者如果垃圾收集得到它,它可能已经消失。

我可以这么说:如果仍然可以得到它,垃圾收集器不会回收这个对象(如果你不能得到它,那么担心这个对象是否已经被 GC 或不是)。

于 2012-06-04T21:53:51.713 回答