描述:模擬兩個售票員同時售票的情況,對電子票箱需要互斥共享。
//售票點(共享數據)
class Clerk{
int ticket = 10;
public synchronized void book(int tk){
if(ticket>=tk) {
System.out.println("book:" + tk);
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
ticket = ticket - tk;
}else{
System.out.println("no ticket");
}
System.out.println("there are:"+ticket);
}
}
//用戶訂票
class Booking extends Thread{
private Clerk clerk;
int num;
public Booking(Clerk clerk,int num){
this.clerk = clerk;
this.num = num;
this.start();//start();
}
public void run(){
clerk.book(num);
}
}
public class ticket {
public static void main(String[] args) {
Clerk clerk = new Clerk();
new Booking(clerk,5);
new Booking(clerk,10);
}
}