Java multi-thread distribution movie ticket

Source: Internet
Author: User
Tags ticket

Code:

1  Public classMainClass {2 3      Public Static voidMain (string[] args) {4 method1 ();5     }6      Public Static voidmethod1 () {7Sellmovie sell =NewSellmovie ();8         9         NewThread (Sell, "American"). Start ();Ten         NewThread (Sell, "glutinous rice"). Start (); One     } A}
1  Public class Model {2     int total = ten; 3 }
1  Public classSellmovieImplementsRunnable {2Model model =NewModel ();3 4 @Override5      Public voidrun () {6          while(Model.total > 0) {7             synchronized(model) {//can only lock reference type8             9                 if(Model.total > 0) {TenSystem.out.println ("Sales Ticket:" + model.total + "+" +Thread.CurrentThread (). GetName ()); One}Else { ASystem.out.println ("Tickets sold out"); -                     return; -                 } themodel.total--; -             } -System.out.println ("......")); -         } +     } -}

This example realizes multi-threading through the implementation of the Runnable interface method, here is the "American Regiment" and "Glutinous rice" two sub-thread Rob ticket process.

Since the lock is only a reference type, the remaining number of votes is shown in the form of the Model class property.

The following results are output:

Ticketing: 10 American
.............
Ticketing: 9 glutinous rice
.............
Ticketing: 8 American
.............
Ticketing: 7 American
.............
Ticketing: 6 glutinous rice
.............
Ticketing: 5 American
.............
Ticketing: 4 glutinous rice
.............
Ticketing: 3 American
.............
Ticketing: 2 American
.............
Ticketing: 1 American
.............
Tickets sold out.

Java multi-thread distribution movie ticket

Related Article

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.