当前位置:网站首页>Concurrent operation -- the difference between reentrantlock and synchronized

Concurrent operation -- the difference between reentrantlock and synchronized

2022-06-09 03:25:00 RobertTeacher

Concurrent operations

Concurrent operation ——ReenTrantLock and synchronized The difference between .



Synchronized and ReenTrantLock The differences and use scenarios

The problem of locking multiple threads in high concurrency environment .


One 、synchronized and ReenTrantLock The difference between ?

1、synchronized

Pessimistic locking , Reentrant lock , Not fair lock , Unable to get the state of the lock , It will cause other threads to block ,java Built in keywords , Implicit locking , Simple operation but not flexible enough .

 Insert picture description here
 Insert picture description here

2、ReenTrantLock

Pessimistic locking , Reentrant lock , It can be fair lock or unfair lock ( When creating, pass in parameters true Create fair locks ,false and null It's all unfair locks ), Manual lock and unlock required , The unlocking operation should be placed in finally In the code , Make sure the thread releases the lock correctly , The difference at the bottom is AQS Of state and FIFO Queue to control locking .

Two 、synchronized and ReenTrantLock Usage scenarios of

1、synchronized

In general, the use of concurrency scenarios is sufficient , Can be placed on methods that are executed recursively , And don't worry about whether the thread can release the lock correctly in the end .

2、ReenTrantLock

When used in complex scenarios, the number of times to repeatedly acquire a lock must be the same as the number of times to repeatedly release a lock during reentry , Otherwise, other threads may not be able to obtain the lock .


summary

The main difference is ReenTrantLock You can control the lock and view the lock status more flexibly ,synchronized Unable to determine whether to acquire the lock state .

原网站

版权声明
本文为[RobertTeacher]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/160/202206090323358228.html