3

我有一堂课

class Foo{

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

我有 2 个对象Foo.get()f.getMore()在 2 个不同的线程 t1 和 t2 中运行。我有一个问题,当线程 t1 在类上获得锁定时,线程 t2 是否可以访问方法 getMore,或者由于类对象被 t1 锁定,是否会阻止 t2 获得对该方法的访问和锁定。

4

4 回答 4

3

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

于 2013-01-07T11:13:39.857 回答
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
     }

}
于 2013-01-07T11:17:27.917 回答
1

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

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

于 2013-01-07T11:37:59.063 回答
1

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

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

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

于 2013-01-07T11:15:16.393 回答