从不同线程访问数据时丢失对象引用

时间:2019-02-23 15:53:46

标签: java multithreading

我很抱歉编写全部代码,但找不到能解释我问题的单词。

问题: GameHandler创建GameData的对象,并将this作为ITraceble传递。 GameData对象具有ITraceable对象的引用。 GameTask实现了Runnable,因此它将在不同的线程上运行。但是,当我尝试从m_gameData.traceMeNow()内部的任何地方调用GameTask时,我将m_game.m_traceable设为null。

public interface ITraceable {
     public void trace(String a_args);
}

public class GameData {
     ITraceable m_traceable;
     public GameData(ITraceable a_traceable) {
         m_traceable = a_traceable;
     }

     public void traceMeNow() {
         m_traceable.trace("something to trace");    <----- m_traceable ref is NULL.
     }
}

public class GameTask implements Runnable {
    GameData m_gameData;
    public GameTask(GameData a_gameData) {
        m_gameData = a_gameData;
        m_gameData.traceMeNow();                <---Function call from here
    }

    public void run() {
       //something here
    }
}

class GameHandler implements ITraceable {
    public void trace(String a_args) {
         //writting some logs here.
     }

    public void createObjects() {               < ------ Creating objects here
        GameData l_gameData = new GameData(this);
        GameTask l_gameTask = new GameTask(l_gameData);
        //--- Starting GameTask in other Thread ----// 
    }    
}

1 个答案:

答案 0 :(得分:1)

声明变量final:

final ITraceable m_traceable;

这保证了所有线程都将看到分配的值(假设对this的引用不是在构造函数中不安全地发布的,不在这里)。