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