When to use synchronized in Java

后端 未结 2 1681
旧巷少年郎
旧巷少年郎 2020-12-31 12:24

I hope this is going to be enough information, so here it goes. If you need more info, lemme know in the comments.

I have a class that has two inner classes. The inn

2条回答
  •  夕颜
    夕颜 (楼主)
    2020-12-31 12:45

    Wrap everything in outerMethod that you want to run only once in a synchronized block:

    private void outerMethod() {
        synchronized (this) {
            if(!outerMethodHasBeenCalled) {
                // do stuff
            }
    
            outerMethodHasBeenCalled = true;
        }
    }
    

    That way, the first time the method is called, only one thread will be allowed into the synchronized block at a time. The first one will execute the code in the if statement, then set outerMethodHasBeenCalled to true. The other threads will see that it is true, and skip the if code.

提交回复
热议问题