Thread synchronization--Train ticket problem

Source: Internet
Author: User
Tags ticket

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.