Java first met Lock and Synchronized

The difference between Lock and Synchronized

1. Synchronized is a keyword in our java, Lock is a java class

2. Synchronized cannot obtain the state of the lock, Lock can judge whether the lock is obtained

3.Synchronized can automatically release the lock, Lock needs to manually release the lock, if the Lock is not released, our common deadlock will occur

4. Synchronized re-entrant lock, can not be interrupted, unfair; Lock can be re-entered lock, can judge the lock, can be fair

5.Synchronized is suitable for locking a small amount of code synchronization; Lock is suitable for locking a large amount of code synchronization


We simulate a ticket selling system to demonstrate concurrency

1. Three threads sell tickets at the same time, we can see the output information circled in the console, and the remaining tickets are disorderly

Insert picture description here

2. In the past, we only needed to add a keyword synchronized to solve this problem

Insert picture description here


When we first met the Lock lock, we also used the code to demonstrate, mainly looking at the steps of the circle red

Insert picture description here


Guess you like

Origin blog.csdn.net/weixin_45452416/article/details/109814746