Home  >  Q&A  >  body text

java - lock与synchronize的解锁顺序问题?

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

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

谢谢各位!

怪我咯怪我咯2744 days ago726

reply all(2)I'll reply

  • 高洛峰

    高洛峰2017-04-18 10:51:35

    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 .

    reply
    0
  • ringa_lee

    ringa_lee2017-04-18 10:51:35

    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.

    reply
    0
  • Cancelreply