Synchronized with the Lock What is the difference

1. The original constitution

synchronized keyword belongs JVM level

  the monitorenter (bottom layer is accomplished by monitor object, in fact, wait, notify, etc. The method also depends on the monitor object, only the synchronization code blocks and methods to tune the synchronization wait / notify or the like)

  monitorexit

Lock is a concrete class (JUC.locks.Lock) is api-level lock

2. Use

  synchronized without requiring the user to manually release the lock, when synchronized code execution after the system will automatically make the thread releases the lock of occupation

  ReentrantLock the user is required to manually release the lock if there is no initiative to release the lock, it may lead to a deadlock

3. Wait Can I interrupt

  synchronized not be interrupted, unless an exception is thrown or normal operation completed

  1. ReentrantLock can set a timeout interrupt method tryLock (long timeout, TimeUnit unit)

4. Lock is fair

  syn unfair lock

  ReentrantLock default unfair, construction method can be passed a boolean try to be fair

The plurality of lock binding conditions Condition

  syn no

  Re used to implement packet needs to wake up wake up the thread can be precisely wake, rather than all-or-syn or random wake wake

Guess you like

Origin www.cnblogs.com/ergePython/p/12393350.html