The synchronization lock in Ava Multi-threading is mainly implemented by the Synchronized keyword. Let's start with a ticket-buying program.
Packagecom.day04;/** * * @authorAdministrator Problem Description: Use multi-threaded way to simulate multiple windows buy Tickets **/ Public classSalewindowImplementsRunnable {//initial number of votes Private intTicket = 10; @Override Public voidrun () {//get the name of the thread, such as Thread-0, and truncate it thread-take 0 of this number ID, in order to construct the ticket window name below intThreadnum = Integer.parseint (Thread.CurrentThread (). GetName (). SUBSTRING (7)); String Salewindowname= "Sales Window" +Threadnum; //Start buying Tickets while(true) { if(Ticket > 0) { //here in order to demonstrate the problem of out-of-sync, let the thread sleep for a period of time, delay) Try{Thread.Sleep (1000L); } Catch(interruptedexception e) {e.printstacktrace (); } System.out.println (Salewindowname+ "sell" + ticket--+ "Ticket!" "); } Else { Break; } } } Public Static voidMain (string[] args) {//The Sales Window object was createdSalewindow SW =NewSalewindow (); //start a thread and let the first window start buying tickets NewThread (SW). Start (); //start a thread and let the second window start buying tickets NewThread (SW). Start (); //start a thread and let the third window start buying tickets NewThread (SW). Start (); }}
The results of the operation are as follows:
Sales window 2 sold 10th tickets!
Sales Window 1 sold 8th tickets!
Sales Window 0 sold 9th Tickets!
Sales Window 2 sold 7th tickets!
Sales Window 1 sold 6th tickets!
Sales Window 0 sold 5th tickets!
Sales Window 2 sold 4th tickets!
Sales Window 1 sold 3rd tickets!
Sales Window 0 sold 2nd tickets!
Sales window 2 sold 1th tickets!
Sales Window 1 sold No. 0 tickets! 《-----
Sales window 0 Sell-1th ticket! 《------
Can see our program came out of the problem, above the red arrow shown, unexpectedly sell stomach No. 0 votes Ken-1th ticket.
Let's draw a diagram to analyze the following:
Through the above analysis, it is not difficult to draw the cause of the problem.
Understanding of Java Multi-threaded synchronization lock