The difference between synchronized and Lock:
Lock is an interface, and Synchronized is the key word.
2:Synchronized releases the lock automatically, and Lock must release the lock manually.
3:Lock can interrupt the response of the thread waiting for the lock, but Synchronized will not, and the thread will wait all the time.
4: Lock lets you know if a thread has a lock, but Synchronized can't.
5:Lock can improve the efficiency of multiple threads.
6:Synchronized locks classes, methods, and code blocks, while Lock is block-wide
/**
* Synchronized: This control is added to objects that need to be synchronized. Synchronized can be added to methods or to specific code blocks, with brackets indicating objects that need to be locked.
* lock: You need to display the specified start and end locations. The ReentrantLock class is commonly used as a lock, and one ReentrantLock class must be used in multiple threads.
* As an object, the lock can be guaranteed to work.
* lock() and unlock() should be displayed at the locks and unlocks. So unlock() is typically written in the final block to prevent deadlocks.
*
* synchronized originally used the CPU pessimistic lock mechanism, that is, the thread acquired the exclusive lock. Exclusive locks mean that other threads can only rely on blocking to wait for the thread to release the lock.
* When there are many threads competing for locks, it will cause frequent context switching of CPU, resulting in low efficiency.
* Lock uses optimistic locking. The so-called optimistic lock is to complete an operation on the assumption that there is no conflict without locking each time.
* If the conflict fails, try again until it succeeds.
* The mechanism of optimistic lock implementation is CAS operation (Compare and Swap). We can further study the source code of ReentrantLock,
* One of the more important ways to get locks is compareAndSetState. This is actually a special instruction provided by the CPU being invoked.
*/
Let's look at a small example of specific code:
package com.cn.test.thread.lock;