How to realize the function of site ticketing by Java
This article mainly explains "Java how to achieve the site ticketing function", interested friends may wish to take a look. The method introduced in this paper is simple, fast and practical. Next let the editor to take you to learn "Java how to achieve site ticketing function" bar!
The topic requires us to create 5 threads to simulate ticket selling, which of course includes the existence of multithreading, that is, the problem we have to solve, repeated ticket selling and overselling. That is, multiple windows sell the same ticket and windows sell tickets with non-positive numbers.
But this problem can be put aside for a moment. Let's first create the basic threading model and create five threads in the main method to let them run.
Don't say much, put on the code.
Public class Ticket {public static void main (String [] args) {for (int I = 1 world I 0) {System.out.println (code + "_" + tickets--) / / after the ticket has been sold, sleep for a while and wait for other threads to operate try {Thread.sleep (100) } catch (InterruptedException e) {/ / TODO Auto-generated catch block e.printStackTrace () The complete code: public class Ticket {public static void main (String [] args) {for (int I = 1) I 0) {synchronized (lock) {/ / if the tickets are sold out, jump out of if (tickets)