Java 同步和空检查问题

Java 同步和空检查问题,java,nullpointerexception,locking,synchronized,Java,Nullpointerexception,Locking,Synchronized,最近我的代码遇到了一个问题,我有一个线程在执行和运行游戏,另一个线程在检查事件中可能调用的所有事件: 事件示例: try { if (currentMinigame != null) { //Longer code and method execution time would usually be here, //but for the sake of simplicity, I'll just use t

最近我的代码遇到了一个问题,我有一个线程在执行和运行游戏,另一个线程在检查事件中可能调用的所有事件:

事件示例:

       try {
            if (currentMinigame != null) {
            //Longer code and method execution time would usually be here, 
            //but for the sake of simplicity, I'll just use this
                currentMinigame.onEntityShootBow(e);
            }
        } catch (Exception ex) {
            exitEarly(ex);
        }
问题是,在某个时刻,执行小游戏的线程会将currentMinigame设置为null。此时,将在以下行调用空指针:
currentMinigame.OneTityShootbow(e)

有没有一种简单的方法来同步所有这些事件?(大约有25个)

我想用
Object currentMinigameLock=new Object();
已同步(currentMinigameLock)
每一个事件都会有这样的结果,但每次我使用synchronize时;我几乎从来没有看到任何变化,这是一个严重的代码量重构!有没有更简单的方法

谢谢大家!
-Tom

您是否尝试过使用
volatile
关键字?我不知道这是否能解决它,我还没有,如果我错了,请纠正我,但是,小游戏被设置为null实际上是一个预期的功能,如中所示-小游戏不再可用。如果设置为null,Volatile不会导致错误吗?我愿意接受任何变化:)@chancea我了解了volatile的实际功能。考虑到我真的应该知道这一点,真是愚蠢。但是我真的不明白volatile如何解决这个问题?使变量
volatile
同步应该意味着每个线程将直接从主内存访问它,因此一旦游戏线程使其
为null
,另一个线程将立即看到该更改。然而,我仍然不确定在
currentMinigame!=空
检查,但在
currentMinigame.OneTityShootbow(e)