Answer questions about why there should lock the synchronized

Why java already synchronized access through the synchronized keyword, also need to provide Lock?

synchronized defects
earlier blog has mentioned release the object lock there are two cases:

Program executing the synchronized block of code blocks is released.
Program block synchronization is abnormal, JVM will automatically release locks to handle exceptions.
If you need to wait to obtain the lock thread I / O or by calling the sleep () method is blocked, but still holds the lock, other threads can only dry waiting, so it will affect the efficiency of the procedure. 
Hence the need for a mechanism to prevent waiting threads wait forever known, for example, the value of waiting a period of time or in response to interrupts, Lock lock can be done.

Another example: When there are multiple threads to read and write files, read the phenomenon of conflict and write operations occur, write and write operations may conflict phenomenon, but read and read operations do not conflict occur. But to achieve synchronization using the synchronized keyword, it would cause a problem: If multiple threads are only read, so when a thread is performing a read operation, other threads can only wait can not be read. 
Therefore we need a mechanism to enable multiple threads are only read, not conflict between threads, it can be done by Lock. 
In addition, Lock thread may know there is not a lock, but can not be synchronized.

Summary difference
conclusion, Lock and synchronized with the following differences:

Lock is an interface, and the synchronized keyword.
synchronized automatically release the lock, and Lock must be manually release the lock.
Lock lets wait for the lock thread in response to interrupt, but not synchronized, the thread will wait forever.
By Lock can know there is a thread did not get the lock, and can not be synchronized.
Lock can improve the efficiency of multiple threads read operation.
synchronized can lock classes, methods, and code block, and within the block range Lock

description link: https: //blog.csdn.net/ji519974770/article/details/79736049

Published 740 original articles · won praise 65 · Views 100,000 +

Guess you like

Origin blog.csdn.net/qq_41723615/article/details/104365089