java多线程练习-线程通信-取钱案例
案例需求:
小明打算去提款机上取钱,发现卡上没有钱,这时候他告知妈妈去存钱,妈妈存了钱了,告知小明存好了可以取钱了。小明分多次取钱,每次取100,当发现钱不够100,就等妈妈存钱妈妈每次存钱2000,当发现钱小于100就存钱,并且通知小明取取钱,当大于100就等小明钱不够再存
public class XiaoMing {
private static Byte[] bytes = new Byte[0];
public static void main(String[] args) {
// 取得线程
new Thread(new Runnable() {
@Override
public void run() {
synchronized (bytes) {
while (true) {
Integer money = Mother.getMoney();
System.out.println("小明取钱一次,余额:" + (money)+"元");
if (money==0) {
try {
System.out.println("钱不足,剩余:"+money);
bytes.notifyAll();
System.out.println("等妈妈放钱");
Thread.sleep(5000);
bytes.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
}
}).start();
// 放的线程
new Thread(new Runnable() {
@Override
public void run() {
synchronized (bytes) {
while (true) {
Mother.add();
System.out.println("妈妈放钱成功");
bytes.notifyAll();
try {
bytes.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
}).start();
}
}
class Mother {
private static int count = 0;
static {
add();
}
public static Integer getMoney() {
return count-=100;
}
public static void add() {
count += 2000;
}
}
运行结果: