Java线程和垃圾收集器 [英] Java threads and garbage collector
问题描述
可能重复:
Java线程垃圾收集或不收集
考虑以下课程:
class Foo implements Runnable {
public Foo(){
Thread th =新主题(this);
th.start();
}
public run(){
... //长任务
}
}
如果我们通过做 $ b创建 Foo
的几个实例
$ b
new Foo();
new Foo();
new Foo();
new Foo();
(请注意,我们不保留指向它们的指针)。
-
这些实例是否可以在
run()之前由垃圾收集器 )
结束? (换句话说:对于Foo
对象是否有任何引用
?) -
另一方面,这些实例会在`run()'中的线程结束后被GC
删除,还是我们在浪费内存(内存泄漏)? -
如果1或2是问题,那么正确的方法是什么?
b $ b - 活动线程引用的任何对象被释放。
- 是的,在run()中的线程结束后,GC将删除实例。
Could those instances be removed by the garbage collector before the thread in
run()
ends? (In other words: is there any reference to theFoo
objects?)And, in the other hand, will those instances be removed by the GC after the thread in `run()' ends, or are we wasting memory ("memory leak")?
If either 1. or 2. are a problem, what's the right way to do it?
- Any object which is referenced by an active thread may not be de-allocated.
- Yes, instances will be removed by the GC after the thread in `run()' ends.
- No prob.
感谢
Possible Duplicate:
Java Thread Garbage collected or not
Consider the following class:
class Foo implements Runnable {
public Foo () {
Thread th = new Thread (this);
th.start();
}
public run() {
... // long task
}
}
If we create several instances of Foo
by doing
new Foo();
new Foo();
new Foo();
new Foo();
(note that we don't keep a pointer to them).
Thanks
这篇关于Java线程和垃圾收集器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!