简体   繁体   English

线程进入同步块后可以更改锁吗?

[英]Can we change the lock after thread enter synchronized block?

I am asking this question is just for curiosity, I know it is stupid to do such thing. 我问这个问题只是出于好奇,我知道做这样的事情很愚蠢。

public void doSomething() 
{
      synchronized(object_A){
        count++;
        average = count/total;
      }
}

Now let say I have 2 thread run concurrently (calling function doSomething()), while the first thread already enter the block, let say at the line "count++", the second thread is blocked and waiting the lock. 现在,假设我有2个线程同时运行(调用函数doSomething()),而第一个线程已进入该块,则在“ count ++”行说,第二个线程被阻塞并等待锁。

Now I try to do object_A = new LockObject() (in another thread). 现在,我尝试在另一个线程中执行object_A = new LockObject() )。 Now what happen to thread 1 and thread 2? 现在线程1和线程2发生了什么?

Will thread 2 enter the block? 线程2会进入该块吗? Since it already executed statement "synchronized(object_A)", is it too late to change the lock? 由于它已经执行了语句“ synchronized(object_A)”,因此更改锁是否为时已晚?

Will thread 1 change the lock while in the sync block (assume thread 1 still in the block)? 线程1是否在同步块中会更改锁定(假设线程1仍在该块中)?

就像ignis所说,但是线程2完成后,线程2将看到新的引用,因为它必须刷新所有变量。

The only problem would be data integrity. 唯一的问题将是数据完整性。 Threads will be synchronizing on different locks and the data protected by the locks will have wrong values. 线程将在不同的锁上同步,并且受锁保护的数据将具有错误的值。 Locks are created in the instance initializer's as private final fields or in the constructor of the class. 锁在实例初始值设定项中作为私有final字段或在类的构造函数中创建。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM