Java线程和垃圾收集器 [英] Java threads and garbage collector

查看:88
本文介绍了Java线程和垃圾收集器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


可能重复:

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();

(请注意,我们不保留指向它们的指针)。


  1. 这些实例是否可以在 run()之前由垃圾收集器结束? (换句话说:对于 Foo 对象是否有任何引用
    ?)


  2. 另一方面,这些实例会在`run()'中的线程结束后被GC
    删除,还是我们在浪费内存(内存泄漏)?


  3. 如果1或2是问题,那么正确的方法是什么?

  4. b $ b

    感谢

    解决方案


    1. 活动线程引用的任何对象被释放。

    2. 是的,在run()中的线程结束后,GC将删除实例。


    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).

    1. Could those instances be removed by the garbage collector before the thread in run() ends? (In other words: is there any reference to the Foo objects?)

    2. 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")?

    3. If either 1. or 2. are a problem, what's the right way to do it?

    Thanks

    解决方案

    1. Any object which is referenced by an active thread may not be de-allocated.
    2. Yes, instances will be removed by the GC after the thread in `run()' ends.
    3. No prob.

    这篇关于Java线程和垃圾收集器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆