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 .
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 .
Lock
The locking and unlocking is implemented at the java semantic level, and there is no necessary relationship between lockssynchronized
加解锁是由JVM来实现,在执行完synchronized
块后自行解锁,所有会按照synchronized
’s nesting sequence is unlocked.