29

Possible Duplicate:
Java Synchronized Block for .class

I was reading through an article on synchronization. I am confused on below points and need more clarification

1) For synchronization block. How

   synchronize(this){
    // code
   }

differs from

   synchronize(MyClass.class){
    //code
   }

2) Synchronizing instance method means threads will have to get exclusive lock on the instance, while synchronizing static method means thread will have to acquire a lock on whole class(correct me if I am wrong). So if a class has three methods and one of them is static synchronized then if a thread acquires lock on that method then that means it will acquire lock on the whole class. So does that mean the other two will also get locked and no other method will be able to access those two methods as the whole class is having lock?

4

2 に答える 2

34

MyClass.classthis異なるものであり、異なるオブジェクトへの異なる参照です。

this-は、クラスのこの特定のインスタンスへの参照であり、

MyClass.class-MyClass記述オブジェクトへの参照です。

これらの同期ブロックは、最初のブロックがこのインスタンスを具体的に処理するすべてMyClassのスレッドを同期し、2番目のブロックがどのメソッドが呼び出されたオブジェクトに関係なくすべてのスレッドを同期するという点で異なります。

于 2013-01-24T07:15:03.367 に答える
12

The first example (acquiring lock on this) is meant to be used in instance methods, the second one (acquiring lock on class object) -- in static methods.

If one thread acquires lock on MyClass.class, other threads will have to wait to enter the synchronized block of a static method that this block is located in. Meanwhile, all of the threads will be able to acquire lock for a particular instance of this class and execute instance methods.

于 2013-01-24T07:14:55.837 に答える