gpt4 book ai didi

java - 当 Java 线程结束时,可运行类是否超出范围?

转载 作者:行者123 更新时间:2023-11-29 07:14:25 24 4
gpt4 key购买 nike

如果我创建一个实现 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);

最佳答案

来自source of the Thread class :

/**
* 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(线程正在运行的runnable)的引用。

还有一个bug report #4006245 on bugs.sun.com这是指清除 target 引用。

关于java - 当 Java 线程结束时,可运行类是否超出范围?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10888851/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com