A simulation example of train ticketing system based on Java multithreading
1. Preface
In order to learn multi-threaded sharing and communication, we simulate a train ticketing system, assuming that there are 10 train tickets and three windows (that is, three threads) sell tickets at the same time.
2. Asynchronous code
Print results:
From the above results, it can be clearly seen that since three threads can access one task at the same time, that is, the ticket selling task, there will be an unrealistic problem of - 1 train ticket left. The reason is that assuming that at a certain moment, when tickets is 1, tickets > 0 is true, and thread a runs to tickets -- this line of code, and at this time, 1 has not been subtracted, At the same time, another thread B just runs to the line of tickets > 0. It judges success and starts selling tickets. At this time, thread a subtracts one ticket, tickets = 0, and then thread B subtracts another one, leaving - 1 ticket. Therefore, you need to use the synchronized lock at this time. Ensure that only one thread can execute the ticketing function at a certain time.
3. Synchronization code
Equivalent to:
result:
synchronized:
Synchronized is a keyword in Java. It is a kind of synchronous lock. It modifies the following objects:
1. Modify a code block. The modified code block is called synchronization statement block. Its scope of action is the code enclosed in braces {}, and the object of action is the object calling the code block;
2. Modify a method. The modified method is called synchronous method. Its scope of action is the whole method, and the object of action is the object calling the method;
3. Modify a static method. Its scope of action is the whole static method, and the object of action is all objects of this class;
4. Modify a class. Its scope of action is the part enclosed in parentheses after synchronized. The main object of action is all objects of this class.
The above simulation example of Java multithreaded train ticketing system is all the content shared by Xiaobian. I hope it can give you a reference and support more programming tips.