以下是一个模拟订票业务的程序。BookingClerk类代表自动售票员,其中包含一个订票(booking)方法。假设一开始有10张票可预定。程序运行时产生两个订票客户同时自动向自动售票员订票。请问会出现什么错误?该如何修改?
public class Test
{ public static void main(String args[])
{
BookingClerk bt = new BookingClerk();
new BookingTest(bt, 7);
new BookingTest(bt, 5);
}
}
class BookingClerk {
int remainder = 10;
void booking(int num) {
if (num <= remainder) {
System.out.println("预定" + num + "张票");
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
remainder = remainder - num;
} else {
System.out.println("剩余票不够,无法预定");
}
System.out.println("还剩"+remainder+"张票");
}
}
class BookingTest implements Runnable {
BookingClerk bt;
int num;
BookingTest(BookingClerk bt, int num) {
this.bt = bt;
this.num = num;
new Thread(this).start();
}
public void run() { bt.booking(num); }
}
|
|