如果更改,Java是否将同步阻止? [英] Java will synchronized block if changed?

查看:79
本文介绍了如果更改,Java是否将同步阻止?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

private Object x = new Object();

public void doA() {
   synchronized(x){
       x = new Object();
       //do something
    }
}

public void doB() {
    synchronized(x) {
        //do something 
    }
}

doA()doB()同时被调用,但doA()首先进行.因此B将被阻止,直到doA()完成

lets say doA() and doB() was called simultaneously but doA() is proceeding first. so B will be blocked until doA() is completed

即使doA()修改了x = new x调用中的x,这是否成立?还是在doA() doB()中的此行x = new x之后,由于x已更改,将不再被阻止?

is this true even if doA() modifies x in the x = new x call? or after this line x = new x in doA() doB() will no longer be blocked because x has changed?

推荐答案

发生的事情实际上取决于doA()的运行速度:

What happens would really depend on how quickly doA() gets run:

如果doA()doB()到达其同步块之前更改x的值,则doB()将锁定doA()创建的 new 对象.

If doA() changes the value of x before doB() reaches its synchronized block, then doB() will lock on the new object that doA() created.

如果doB()快速并且在doA()可以更改x的值之前对synchronized(x)部分进行了评估,则doB()将必须等待,直到doA()synchronized块结束.

If doB() is speedy and the synchronized(x) part gets evaluated before doA() can change the value of x, then doB() will have to wait until doA()'s synchronized block finishes.

每当Java使用任何一种方法获取synchronized(x)代码时,它都会评估变量x,该变量为Java提供了一个对象.因此,Java然后尝试锁定该对象,并保持锁定状态.或者,如果该对象上已经有一个锁,它将等待该锁消失. (每当Java到达synchronized(x)代码时,它都会获取变量的值,而忽略变量本身的遗忘,因此以后您可以根据需要更改变量,但是锁定和锁定检查仍会在变量的先前值上进行.)

Whenever Java gets to the synchronized(x) code in either method, it evaluates the variable x, and that variable gives Java an object. So Java then tries to lock on that object, and stay locked on that object. Or, if there's already a lock on that object, it will wait for the lock to go away. (Whenever Java reaches the synchronized(x) code, it takes the value of the variable and ignores forgets the variable itself, so you can change the variable as you please afterwards, but locking and lock checking still happen on the variable's previous value.)

这篇关于如果更改,Java是否将同步阻止?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆