“This is the 9th day of my participation in the Gwen Challenge in November. Check out the details: The Last Gwen Challenge in 2021.”

Thread synchronization: Multiple threads operate on the same resource

Concurrency: The same object is operated on simultaneously by more than one thread

For example: Tens of thousands of people scrambled for 100 tickets at the same time

When dealing with multiple threads, multiple threads access the same object, and some threads want to modify the object, this time will need to thread synchronization, thread synchronization is actually a kind of wait for mechanism, multiple threads need to access the object into the object of waiting for pool forming a queue, waiting in front of after use, Use it in the next thread (for example, you need to queue up one by one to get food at the canteen window, otherwise there may be a fight if everyone does not queue up)

Thread synchronization creates conditions

Queue + lock to ensure thread synchronization security

It can be interpreted as queuing to go to the toilet, one person enters the toilet and locks the door, so that the next person will not rob the toilet while it is still in use. After you finish, the next person will open the lock and enter the toilet

In order to ensure the security of data access in methods, synchronized is added into the access mechanism. When one thread obtains the exclusive lock of an object and monopolizes resources, other threads must wait to release the lock before using it

But there are some problems

  1. A thread holding a lock causes other threads requiring the lock to suspend

  2. In the multi-thread competition, locking and releasing locks will cause many context switches and scheduling delays, resulting in performance problems

  3. If a high-priority thread waits for a low-priority thread to release the lock, priority inversion can occur, causing performance problems

In this article juejin.cn/post/702674… A buying a ticket demo in it demonstrates a kind of unsafe buying a ticket. When three people buy a ticket at the same time, they will grab the same ticket, but the actual situation is that a ticket can only be obtained by one person

Each thread has its own working memory, and when the thread sees the remaining ticket, it will bring the remaining ticket to its own thread, thinking that the ticket is still available