public class BreakfastQueue { private static int count = 0; private static int money = 0; private static Object lock = new Object(); public static void main(String[] args) { BreakfastShop shop = new BreakfastShop(); new Thread(new Customer("张先生", 20, shop)).start(); new Thread(new Customer("王先生", 10, shop)).start(); new Thread(new Customer("李先生", 5, shop)).start(); } static class BreakfastShop { public void sell() { synchronized (lock) { while (count >= 3) { try { lock.wait(); } catch (InterruptedException e) { e.printStackTrace(); } } count++; money += 5; System.out.println(Thread.currentThread().getName() + " 买了早餐,共有 " + count + " 人排队,收入 " + money + " 元"); lock.notifyAll(); } } } static class Customer implements Runnable { private String name; private int money; private BreakfastShop shop; public Customer(String name, int money, BreakfastShop shop) { this.name = name; this.money = money; this.shop = shop; } @Override public void run() { while (true) { if (money >= 5) { shop.sell(); money -= 5; } else if (money == 0) { System.out.println(name + " 没钱了,回家了"); break; } else { System.out.println(name + " 余额不足,等待中..."); try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } } } } } }优化以上代码
时间: 2024-03-11 15:48:24 浏览: 93
以下是改进后的代码:
```java
public class BreakfastQueue {
private int count = 0;
private int money = 0;
private Object lock = new Object();
public static void main(String[] args) {
BreakfastShop shop = new BreakfastShop();
new Thread(new Customer("张先生", 20, shop)).start();
new Thread(new Customer("王先生", 10, shop)).start();
new Thread(new Customer("李先生", 5, shop)).start();
}
class BreakfastShop {
public void sell() {
synchronized (lock) {
if (count >= 3) {
try {
lock.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
count++;
money += 5;
System.out.println(Thread.currentThread().getName() + " 买了早餐,共有 " + count + " 人排队,收入 " + money + " 元");
lock.notifyAll();
}
}
}
class Customer implements Runnable {
private String name;
private int money;
private BreakfastShop shop;
private boolean flag = false;
public Customer(String name, int money, BreakfastShop shop) {
this.name = name;
this.money = money;
this.shop = shop;
}
@Override
public void run() {
while (true) {
synchronized (lock) {
if (flag) {
try {
lock.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
continue;
}
if (money >= 5) {
shop.sell();
money -= 5;
flag = true;
} else if (money == 0) {
System.out.println(name + " 没钱了,回家了");
break;
} else {
System.out.println(name + " 余额不足,等待中...");
try {
lock.wait(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
}
}
}
```
改进的地方主要有:
1. 将静态变量 count 和 money 改为实例变量,这样可以支持多个早餐店同时运行。
2. 在 sell() 方法中使用 if 判断代替 while 循环,这样可以避免虚假唤醒问题。
3. 在 Customer 类中加入一个 flag 变量,标记当前顾客是否已经购买,避免重复购买。
4. 将 lock 对象改为实例变量 this,这样可以避免多个早餐店之间的互相干扰。
5. 在 Customer 类中加入了一个 while 循环,避免了顾客在购买之后还未离开店铺就再次购买的情况。同时,使用了 lock.wait() 来等待顾客购买完毕之后再继续购买。
阅读全文