Java multi thread simulation ticketing program and thread safety
In the knowledge of threads in Java, the ticketing program is very classic. There are also some problems in the program!
Demand: simulate three windows and sell 100 tickets at the same time.
Question 1: Why are 100 tickets sold and 300 tickets sold?
Reason: because tickets is non-static, one copy of non-static member variable data will be maintained in each object, and three thread objects will have three copies@ H_ 404_ 9@ solution: share the tickets to three thread objects. Use static modifier.
Question 2: is there a thread safety problem@ H_ 404_ 9@
Solution to thread safety problem: sun provides thread synchronization mechanism to solve this kind of problem.
Java thread synchronization mechanism:
Method 1: synchronize code blocks
Mode 2: synchronization function