我很抱歉编写全部代码,但找不到能解释我问题的单词。
问题:
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 ----//
}
}
答案 0 :(得分:1)
声明变量final:
final ITraceable m_traceable;
这保证了所有线程都将看到分配的值(假设对this
的引用不是在构造函数中不安全地发布的,不在这里)。