Java lock locks specific objects and javalock locks
Since lock does not lock a specific object, how can we achieve the same effect as synchronized synchronization blocks?
Answer: assign a lock to each object needing to be locked.
Example:
List <User> users = new ArrayList <> (); // synchronize the synchronized (users. get (0) {// do something sync} // synchronize the users lock of an object. get (0 ). lock. lock (); // lock synchronization try {// do something sync} finally {users. get (0 ). lock. unlock (); // unlock} class User {/*** assigns a Lock to the user object */public lock Lock = new ReentrantLock (); public int id; public String name ;}
Efficiency Comparison (MACHINE: macOs10.12.5, i5 processor, 8 GB memory)
// Thread_count synchronized lock
// 10 1-2 ms 2-3 ms
// 100 8-12 ms 7-12 ms
// 1000 68-94 ms 64-85 ms
// 10000 642-713 ms 687-773 ms
// 100000 5500 ms 5600 ms
// 1000000 54 s 52 s
We can see that the efficiency is almost the same! Therefore, if you must use lock, use it. Otherwise, the synchronized keyword is good and easy to understand.