模拟两个人在一个售票窗口买票,每人买一张票,售票员没有零钱,电影票是50元一张。李四有100元钱,买票时,售票员找不开,此时必须等待李三买票,李三有50元钱,正好够买一张电影票,不用找零。所以,最终的买票顺序应该是李三先买,李四后买。
package cn.bt;
public class BuyingTickets implements Runnable { //售票线程类
String name1, name2;
int fifty = 0, hundred = 0;
public BuyingTickets(String name1, String name2) {
this.name1 = name1;
this.name2 = name2;
}
@Override
public void run() {
String tName = Thread.currentThread().getName();
if (tName.equals(name1)) {
sell(50); //李三给售票员50块
} else if (tName.equals(name2)) {
sell(100); //李四给售票员100块
}
}
public synchronized void sell(int money) { //售票同步方法
String tName = Thread.currentThread().getName();
if (50 == money) {
fifty += 1;
System.out.println(tName + "给售票员50元钱,不必找钱!");
} else if (100 == money) {
while (fifty < 1) {
try {
System.out.println(tName + "给售票员100元钱!\n售票员请" + tName + "等一会!\n");
wait();
System.out.println(tName + "等待结束,继续买票!");
} catch (Exception e) {
}
}
hundred += 1;
fifty -= 1;
System.out.println(tName + "给售票员100元钱!售票员找给" + tName + "50元钱!\n");
}
notifyAll();
}
public static void main(String[] args) {
String name1 = "李三";
String name2 = "李四";
BuyingTickets bt = new BuyingTickets(name1, name2);
new Thread(bt, name1).start();
new Thread(bt, name2).start();
}
}