为什么扫描程序的内存永远保留在堆中?

问题描述 投票:0回答:2

在我标记为// D的行中,对象实例扫描程序只能使用一次。但是只要程序播放,它的内存就会一直保留在堆中(这是永远的)。为什么垃圾收集器不会删除此实例对象?我如何更改代码,以便垃圾收集器将由于程序而删除此实例?谢谢

package Try;

import java.util.Random;
import java.util.Scanner;

public class Foo1 extends Thread {

    private int min_, max_;
    Foo1(int max, Integer min) {

    max_ = max;
    min_ = min.intValue();
    }

    public void run() {

        Random rand_gen = new Random();
        while(true) {
            try {
                Thread.sleep(rand_gen.nextInt(max_-min_) + min_);
            }catch (InterruptedException e){
                e.printStackTrace();
            }
            System.out.println("you got new message");
        }
    }

    public static void main(String[] args){

        System.out.println("Insert 1 to start"); 

        Scanner sc = new Scanner(System.in); // D

        int i = sc.nextInt();

        if (i == 1) {
            Foo1 f1;
            int max = 1000;
            Integer min = new Integer(1000);
            Foo1 f2 = new Foo1(max, min);
            f1 = f2; // A
            f1.start();
        }
    }
}
java multithreading garbage-collection garbage
2个回答
0
投票

我如何更改代码,以便垃圾收集器将由于程序而删除此实例?

您应将对象的值设置为null。然后,垃圾收集器将释放该对象使用的堆内存。

public static void main(String[] args){

    System.out.println("Insert 1 to start"); 

    Scanner sc = new Scanner(System.in); // D

    int i = sc.nextInt();
    sc = null;

    if (i == 1) {
        Foo1 f1;
        int max = 1000;
        Integer min = new Integer(1000);
        Foo1 f2 = new Foo1(max, min);
        f1 = f2; // A
        f1.start();
    }
}

之所以不能在方法末尾自动删除它,是因为您在主方法中对其进行了初始化。换句话说:main方法在应用程序停止时停止。


0
投票

[C0使用后需要关闭它:

Scanner

更好的是使用try-with-resources如下:

int i = sc.nextInt();
sc.close();

请注意,int i; try (Scanner sc = new Scanner(System.in)) { i = sc.nextInt(); } 关闭扫描仪并释放资源,而sc.close()删除对扫描仪的引用,但是资源可能仍保持打开状态。

© www.soinside.com 2019 - 2024. All rights reserved.