我要评分
获取效率
正确性
完整性
易理解

Synchronized Synchronization Lock

The synchronized keyword provides a built-in lock mechanism in the Java language to meet the requirements of Java atomicity and visibility. Each object has an associated monitor for mutually exclusive access. If two threads attempt to "synchronize" on the same object, one thread needs to wait for the synchronization of the other to complete.

  • Synchronization method

    The synchronized method is declared by adding the synchronized keyword to the method declaration. The following code indicates that only one thread can execute func() at a time and other threads must wait.

    public synchronized void func();
  • Synchronize code blocks.

    When concurrent threads access code blocks in an object, only one thread can execute the code block at a time. The other thread can execute the code block only after the current thread completes execution of the code block.

    synchronized(object) {//Code that can be accessed}