Begain with a Question: as we know, the sychronized key work can be applied on method. So What if there are two sychronized method (methodA() and methodB()) in one class, is it possible for two different threads (thread1 and thread 2) call these two method at the same time?
e.g. thread1 call methodA() and thread2 call methodB() at the same time.
以一个问题开头,众所周知synchronized关键字可以作用在方法上。如果一个类中有两个synchronized方法 (methodA() and methodB()),那么是否可以有两个不同的线程(thread1 and thread 2) 同时调用这两个不同的方法呢?
具体举例为:thread1调用methodA()的同时,thread2去调用执行methodB()
The answer is nagetive. The synchronized method is like synchronization block, and we can see a synchronized method as a synchronization block like below.
答案是否定的。同步方法通过可以如下的形式看作等效的。
synchronized void method() { // do sth }
void method() { synchronized (this) { // do sth } }
So, how does it achive? Let's dig it more deeply. Firstly, there's some thing about Jvm we should know which the existence form of one object in Jvm.
所以,这些是如何实现的呢?理解它需要更多挖掘。首先需要了解的是一个对象是如何在JVM中存在的。
A java object whatever it is, the instance would always be instantialed by c code and extist in heap. Apart from the params defined in java class, the instance in heap form with some extra info which is called object head. In object head, there're two important thing, one is the class that the object belongs to, and the other is lock.
一个对象,无论它是哪个类,它都是通过c代码构建在堆中的。这个对象上,处理在java类中定义的参数,堆中的对象还拥有额外的对象头信息。在对象头中,有两个重要的内容,一个是这个对象所属的类信息,另一个是锁lock。
As for the statement "sychronized(object)", it would be compiled into two instruction which are "enterlock" before synchorinzed code and "exitlock" after synchronized code. And they are performed by the lock in object head we have mentioned before. The lock in object head is able to record the thread reference. And when it really holds a theard reference, that means this object is locked by the thread and can only be operated by the thead. Therefor, the process of holding and releasing the thread reference is the process of lock and unlock which makes up the synchronization.
对于"sychronized(object)"的语句,它会被编译成两个指令,一个是在同步块代码前的"enterlock",另一个是在同步块代码后的"exitlock", 它们通过前文提到的lock信息进行工作。lock信息是一个持有的线程对象的信息。当锁lock持有一个线程对象时,就意味着这个对象被该线程加锁,此时,只有这个线程可以对它进行操作。因此,这个锁lock对线程对象的持有与释放的过程,就是线程对对象的加锁与解锁的过程,这也同时就是同步的实现方式。
So, to answer the question below, two different thread reference can not be hold by one lock. And in the question, the lock in object head of the class object can not hold theard1 and thread2 at the same time. That makes thread1 and thread2 can't operate methodA() and methodB() at the same time.
所以,回答上面提到的问题。一个锁lock无法同时持有两个不同的线程对象,即在问题中,一个类对象的对象头中的锁lock无法同时持有theard1 and thread2,那么这个类的同步方法methodA()和methodB()便无法同时被thread1和thread2执行。