1. Cause of Problem 1.1
When multiple threads call the same variable, because only one thread is running at a time, some threads change the variable, but the other threads are running according to the previous variable.
1.2 Specific questions
Two ticket-selling threads, tickets do not buy tickets for 0 o'clock, but when the two threads are in the method of buying tickets, one thread has sold out the ticket, but another thread of the ticket process is still running, so began to sell negative votes
1.3 Solutions
Using synchronous code blocks
2. Code
1 Public classDemo {2 Public Static voidMain (string[] args) {3Ticket T =NewTicket ();4 NewThread () {//Thread One5 6 @Override7 Public voidrun () {8 Try {9 This. Sleep (10);Ten}Catch(interruptedexception e) { One //TODO auto-generated Catch block A e.printstacktrace (); - } - T.saleticket (); the } - }.start (); - - NewThread () {//thread Two + - @Override + Public voidrun () { A Try { at This. Sleep (100); -}Catch(interruptedexception e) { - //TODO auto-generated Catch block - e.printstacktrace (); - } - T.saleticket (); in } - }.start (); to + } - } the * classTicket { $ Private intTicket = 100;Panax Notoginseng Public voidSaleticket () { - while(Ticket! = 0) { the synchronized(Ticket.class) { +System.out.println ("... This is the first "+ ticket--+" ticket.); A } the } + } -}
Thread synchronization--Train ticket problem