8.17 ReentrantLock (reentrant lock)

1.

2. Advantages of ReentrantLock over synchronized

a. Provide a tryLock method to lock. For the lock operation, if the lock is unsuccessful, it will block and wait (dead wait). For the tryLock operation, if the lock is unsuccessful, it will return false, and the waiting time can be set.

b. Use the constructor to set parameters to select fair locks and unfair locks.

c. It also has a waiting notification mechanism, which is completed with the Condition class. It is more powerful and can wake up the specified thread.

3. Disadvantages of ReentrantLock compared to synchronized

a.unlock is easy to miss, it is recommended to use it with finally.

b. The synchronized lock object is any object, and the ReentrantLock lock object is the lock itself. Multiple threads calling the lock method for different ReentrantLock will not cause lock competition.

c. There is no automatic optimization mechanism.

4. In actual development, synchronized is preferred.

Guess you like

Origin blog.csdn.net/m0_73345579/article/details/132140388