Public Station (String name) {
super(name); }
A Boolean flag=true;
Private Object lock=new Object ();
Static int tics=1;
Public void the run () {
While (flag) {
Synchronized (lock) {
Try {
Station. Sleep (200);
{} catch InterruptedException (e)
e.printStackTrace();
}
If (tics<=20)
{
System. Out.println (Station. CurrentThread (). The getName () + "is to sell the first" + tics++ + "ticket.. ");
}
The else {
System. Out.println (" ticket sold out!" );
Flag=false;
}
}
}
}
}
Public class Sale {
Public static void main (String args []) {
Station Station1=new Station (" window 1 ");
Station Station2=new Station (" window 2 ");
Station Station3=new Station (" window 3 ");
Station1. Start ();
Station2. Start ();
Station3. Start ();
}
}
run results:
Window 2 3 are selling tickets..
Window 1 2 are selling tickets..
3 ticket window 1 are selling..
The window is 3 tickets for 4..
The window is 2 tickets for 5..
Window 1 are tickets for 5..
6 ticket window 3 are selling..
Windows 7 2 are selling tickets..
Windows 7 1 are selling tickets..
Windows 8 3 are selling tickets..
Window 1 are tickets for 9..
The window is 2 tickets for 9..
Window 1 are tickets for the 11th..
The window is 2 tickets for 12..
10 ticket window 3 are selling..
Window 1 are tickets for the 13th..
The window is 2 tickets for 13..
14 ticket window 3 are selling..
Window 2 tickets are sold 15..
Window 1 are tickets for the 16th..
17 ticket window 3 are selling..
18 window 2 are selling tickets..
Window 1 are tickets for the 19th...
Window 3 tickets are sold 20..
Sold out!
Sold out!
Sold out!
What is wrong? Repeat the votes, "sold out" repeated three times??
CodePudding user response:
You new three Station, each Station has its own attribute lock, do you think of the three lock is the same object? Is not the same object, you lock it make sense? Multi-threaded to share an object, lock the Shared object lock to be meaningful,So, the easiest way is to change the lock to the static