假设定义了一个局部变量,然后传递给 Thread 构造函数,在那里它被保存为该线程的私有字段。然后,线程开始连续运行(基本上是永远),而原始方法结束。
局部变量引用没了,但是GC有没有考虑到Thread对象存储的引用?
我的场景类似于这个示例片段:
...
public static void Main(String... args) {
Foo foo = new Foo()
MyThread thread = new MyThread(foo)
ExecutorService executor = Executors.newSingleThreadExecutor();
executor.execute(thread)
}
...
public class MyThread implements Runnable {
private Foo foo;
public MyThread(Foo foo) {
this.foo = foo;
}
public void run() {
while (true) {
this.foo.print(); // << throws NullPointerException
sleep(...)
}
}
}
慕尼黑的夜晚无繁华
相关分类