2013-01-07 154 views
2

我有一个类静态同步方法与非静态同步方法

class Foo{ 

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

我有2个物体Foo.get()f.getMore()在2个不同的线程T1和T2上运行。我有一个dobuts,当线程t1在类上锁定时,线程t2可以访问方法getMore,或者阻止t2获取对方法的访问和锁定,因为类对象被t1锁定。

+0

[Java中的并发:同步静态方法]的可能重复(http://stackoverflow.com/questions/5443297/concurrency-in-java-synchronized-static-methods) – bmargulies

回答

2

静态方法将在Class对象上进行同步,而不是实例对象。你有2个锁在2个不同的物体上操作。在上面的场景中,不会有阻止行为。

0

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

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

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

2

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

它类似于

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 
    } 

} 
0

synchonized static method将获得锁java.lang.Class对象ct代表Foo类别。

synchonized instance method将获得Actual对象的锁定。