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