java - lock与synchronize的解锁顺序问题?
怪我咯
怪我咯 2017-04-18 10:49:35
0
2
757

在学习lock与synchronize的区别时,看到这样一句话:“ lock更灵活,可以自由定义多把锁的枷锁解锁顺序(synchronized要按照先加的后解顺序)”。请问这里:

1.lock的自由定义多把锁的枷锁解锁顺序怎么理解?
2.synchronized要按照先加的后解顺序怎么理解?

谢谢各位!

怪我咯
怪我咯

走同样的路,发现不同的人生

reply all(2)
小葫芦

Lock is an interface, and the most commonly used implementation is ReentrantLock. One of its flexibility is that it can set the fair parameter.

ReentrantLock with synchronized and fair=false cannot determine the locking order. In other words, threads A, B, and C all lock the object. The first time they try to lock is A, then B, and finally C. Then when A unlocks the object, it cannot be determined whether B or C will lock the object next.

If you use ReentrantLock with fair=true, the situation is determined: when A unlocks the object, since B tries to lock the object before C, B must lock it next, and only when B unlocks it is C's turn .

左手右手慢动作
new lock1
new lock2

lock1.lock();
lock2.lock();
...
lock2.unlock();
lock1.unlock();

LockThe locking and unlocking is implemented at the java semantic level, and there is no necessary relationship between locks

synchronized(obj1){
    synchronized(obj2){
        ...
    }
}

synchronized加解锁是由JVM来实现,在执行完synchronized块后自行解锁,所有会按照synchronized’s nesting sequence is unlocked.

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template