静态同步方法与非静态同步方法

时间:2013-01-07 11:11:29

标签: java static synchronized non-static

我有一个班级

class Foo{

    static synchronized get(){}
    synchronized() getMore(){}
}

我有2个对象Foo.get()f.getMore()在2个不同的线程t1和t2中运行。我有一个dobuts是否当线程t1在类上有锁时,线程t2可以访问方法getMore,或者因为类对象被t1锁定而无法获取访问权限和锁定方法。

4 个答案:

答案 0 :(得分:3)

静态方法将在Class对象上进行同步,而不是实例对象。您有2个锁在两个不同的对象上运行。在上面的场景中,没有阻止行为。

答案 1 :(得分:3)

静态同步--->级别锁定(类级别范围)

类似于

synchronized(SomeClass.class){
 //some code
}

简单同步--->实例级锁定

示例:

class Foo{

     public static synchronized void bar(){
         //Only one thread would be able to call this at a time  
     }

     public synchronized void bazz(){
         //One thread at a time ----- If same instance of Foo
         //Multiple threads at a time ---- If different instances of Foo class
     }

}

答案 2 :(得分:1)

synchonized锁定一个对象,static synchronized锁定代表该类的对象。

t1和t2可以同时调用这些方法,除非它们不能都在static synchronized方法中,除非除了一个线程以外只有wait()

注意:t1和t2可以同时为不同的对象调用getMore()

答案 3 :(得分:1)

synchonized static method将获取代表Foo类关联的java.lang.Class对象的锁。

synchonized instance method将获取实际对象的锁定。