同步块如何实现同步

时间:2014-04-09 15:18:25

标签: java multithreading synchronization mutex

在Java中,如果方法由synchronized关键字限定,则它确保单个线程可以随时通过操作对象monitor来访问此方法,以便在线程进入同步时它锁定monitor的方法,以便所有其他线程知道它已被另一个线程锁定。

我的问题是同步块如何实现同步,我的意思是没有与此同步块关联的monitor所以它用于确定该块是否已经执行的指示是什么?我迷失在这里。

1 个答案:

答案 0 :(得分:3)

每个对象都有一个与之关联的隐式锁。进入同步块时,进程必须先获取对象的锁定才能继续。退出同步块时会返回锁定。

public class SomeClass {
   private Object mutex = new Object();
   public static synchronized void method1() {
      // static methods aquire the class level lock for SomeClass 
   }
   public synchronized void method2() {
      // aquire the lock associated with 'this' instance (of SomeClass)
   }
   public void method3() {
      synchronized (mutex) {
         // aquire the lock of the mutex object
      }
   }
}
相关问题