静态方法内的同步块将获取类级别锁或对象级别锁

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了静态方法内的同步块将获取类级别锁或对象级别锁相关的知识,希望对你有一定的参考价值。

在下面的代码片段中,我有一个问题。线程将获取类级别锁或对象级别锁?

private static Object lock=new Object();
private static Object lock2=new Object();

public static void m1()
synchronized(lock)
//statements



public static void m2()
synchronized(lock2)
//statements


答案

每个对象都有一个“监视器”。使用同步块时,请指定要在其上同步其监视器的实例。除了同步的,还有同步的方法。同步的[[instance方法将获取该方法在其上被调用的实例的监视器,而同步的[[static方法将获取该封闭类的java.lang.Class对象的监视器。]public class Foo private static final Object STATIC_LOCK = new Object(); private final Object instanceLock = new Object(); public static void bar() synchronized (STATIC_LOCK) // acquires monitor of "STATIC_LOCK" instance // guarded code public static synchronized void baz() // acquires monitor of "Foo.class" instance // guarded code public void qux() synchronized (instanceLock) // acquires monitor of "instanceLock" instance // guarded code public synchronized void quux() // acquires monitor of "this" instance // guarded code

另一答案
monitor
另一答案
public class Test private static Object lock2 = new Object(); public synchronized void m1() // Lock on current object instance(this) as this is an instance method public synchronized static void m2() // Lock at class level as this is a static method public static void m3() synchronized (lock2) // Lock on `lock2` object. It doesn't make a difference if this method // is static or not at the time of acquiring lock on a given object here

以上是关于静态方法内的同步块将获取类级别锁或对象级别锁的主要内容,如果未能解决你的问题,请参考以下文章

博客2

Java中锁的级别

事务隔离级别

在监视器(Monitor)内部,是如何做线程同步的?程序应该做哪种级别的同步?

ACID数据库隔离级别

多线程