首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >在Java中,一个对象在我杀死它的持有者之后还活着吗?

在Java中,一个对象在我杀死它的持有者之后还活着吗?
EN

Stack Overflow用户
提问于 2018-06-05 06:27:08
回答 2查看 112关注 0票数 0

我为下一个bug苦苦挣扎了好几个小时。我的程序结构如下

main函数初始化一个Game对象并调用startMainWindow(),后者初始化一个GameLogic logic对象和一个MainWindow对象(将logic作为参数传递给它,还将this作为参数传递给它)。这两个对象都是 startMainWindow()中的局部变量。

问题是,假设玩家玩完游戏后,我想启动高分图形用户界面,我从MainWindow调用_game.startHighScoreWindow()。问题是GameLogic对象一直在运行!通过在GameLogic.actionPerformed()中输入控制台写命令,我可以轻松地检查它。它不会从内存中释放。即使我在_game.startHighScoreWindow()之前调用this.dispose();,也会发生这种情况。

为什么_gameLogic还在内存中?

下面是一些代码:

PacmanGame:

代码语言:javascript
复制
public void startMainWindow(int levelIndex, int levelsDone, int score) {
    gameGui = null; //desperate attempt
    highScoreGui = null;
    mainMenuGui = null;
    spaceGui = null;
    gameLogic = null;
    System.gc();

    gameLogic = new GameLogic(_sprites, _levels[levelIndex], levelsDone, score);

    gameGui = new MainWindowGui(this, gameLogic, _sprites, _levels);
}

public void startHighscoreGui(int score, String time) {
        gameGui = null;
        highScoreGui = null;
        mainMenuGui = null;
        spaceGui = null;
        gameLogic = null;
        System.gc();

        highScoreGui = new HighscoreGui(this, score, time);
    }

MainWindow:

代码语言:javascript
复制
public class MainWindow extends JFrame implements KeyListener {

    private PacmanGame _game;
    private GameLogic _gameLogic;
    private GamePanel _gamePanel; //JPanel
    private ToolbarPanel _toolbarPanel; //JPanel
    private Sprite[] _sprites;
    private Level[] _levels;

    public MainWindow(PacmanGame game, GameLogic gameLogic, Sprite[] sprites, Level[] levels) {
        // create our window
        super("Pacman");

        // initialize fields
        _game = game;
        _sprites = sprites;
        _gameLogic = gameLogic;
        _levels = levels;
        this._gamePanel = new GamePanel(_gameLogic, _sprites);
        this._toolbarPanel = new ToolbarPanel(_gameLogic, sprites, this);
        ...
    }

    public void playerWon(String time) {
        Level levelObj = _gameLogic.getLevelObject();
        int nextLevelIndex = (levelObj.getNum()) % 3;

        if(_gameLogic.getLevel() == 3) //done!
        {
            this.dispose();
            _game.startHighscoreGui(_gameLogic.getScore(), time);
        }
        else //next level
        {
            _gameLogic.nextLevel(_levels[nextLevelIndex]);
        }
    }

编辑:在一次孤注一掷的尝试中,我尝试在PacmanGame中创建所有的GUI和GameLogic静态变量,然后每次在PacmanGame中调用函数时将它们设置为null。它保持与以前一样的行为,也就是说,所有这些对象都是每个函数的本地对象。

EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/50689605

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档