Multi-threaded safety issues and solutions

Multi-threaded safety issues and solutions

1. Thread safety
If there are multiple threads running at the same time, and these threads may run a piece of code at the same time. The result of each program run is the same as the result of a single-threaded run, and the values ​​of other variables are also the same as expected. This is thread safety

2. The thread safety issue (through a case)
simulates the movie theater ticket sales process. Suppose there are only 100 seats in a movie, so this movie can only sell 100 tickets. When multiple windows sell tickets, multiple windows operate these 100 tickets at the same time. When one ticket is sold, the number of tickets is modified. Perform thread-safe operations, there will be duplicate tickets or no tickets sold (sold -1)

The root cause of the thread safety problem: shared data may be modified concurrently, that is, when one thread reads it, another thread is allowed to modify it.

3. Solution

1) Use synchronization code block
Insert picture description here
2) Use synchronization method
Insert picture description here
3) Use static synchronization method
Insert picture description here
4) Use lock
Insert picture description here

Guess you like

Origin blog.csdn.net/weixin_49092628/article/details/110261429