当前位置:网站首页>The difference between synchronized and lock

The difference between synchronized and lock

2022-07-04 06:57:00 No trace after wind 2018

Synchronized and Lock The difference between

  1. First synchronized yes java Built in keywords ,Lock It's a java Interface ;

  2. synchronized Unable to determine whether to acquire the lock state ,Lock It can be judged whether the lock is obtained (trylock);

  3. synchronized Will automatically release the lock ( The lock will be released after the synchronization code is executed or an exception occurs ),Lock Need to be in finally Release the lock by hand (unlock() Method release lock ), Otherwise, it is easy to cause thread deadlock ;

  4. use synchronized Two threads of keyword 1 And thread 2, If the current thread 1 Gets the lock , Threads 2 Thread waiting . If the thread 1 Blocking , Threads 2 Then I will wait all the time , and Lock The lock doesn't have to wait , If an attempt to acquire a lock fails , Threads can end without waiting all the time ;

  5. synchronized The lock of can be re entered 、 Non interruptible 、 Unfair , and Lock The lock can be reentered 、 interruptible (interrupt)、 Fair enough ( Either way )

  6. Lock Lock is suitable for a large number of synchronized code synchronization problems ,synchronized Locks are suitable for synchronization problems with a small amount of code .

原网站

版权声明
本文为[No trace after wind 2018]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/02/202202141554182107.html