What does 'synchronized' mean?

后端 未结 17 1630
广开言路
广开言路 2020-11-22 00:13

I have some questions regarding the usage and significance of the synchronized keyword.

  • What is the significance of the synchronized
17条回答
  •  难免孤独
    2020-11-22 00:40

    Here is an explanation from The Java Tutorials.

    Consider the following code:

    public class SynchronizedCounter {
        private int c = 0;
    
        public synchronized void increment() {
            c++;
        }
    
        public synchronized void decrement() {
            c--;
        }
    
        public synchronized int value() {
            return c;
        }
    }
    

    if count is an instance of SynchronizedCounter, then making these methods synchronized has two effects:

    • First, it is not possible for two invocations of synchronized methods on the same object to interleave. When one thread is executing a synchronized method for an object, all other threads that invoke synchronized methods for the same object block (suspend execution) until the first thread is done with the object.
    • Second, when a synchronized method exits, it automatically establishes a happens-before relationship with any subsequent invocation of a synchronized method for the same object. This guarantees that changes to the state of the object are visible to all threads.

提交回复
热议问题