bank(代表银行)
package test2022;
public class bank {
private int money;
public bank() {
money=0;
}
public synchronized void save(int money) { //作为存钱函数
this.money+=money;//从原来基础上,添加新存进去的钱
System.out.println(Thread.currentThread().getName()+"存了:"+money+",余额:"+this.money);//money为新存进去的,this.money为余额
notify();//通知取钱线程,因余额不足而被阻塞的取钱线程
}
public synchronized void take(int money) { //作为取钱函数
//先判断你卡里有没有那么多钱
if(this.money>=money) { //余额比要取的多
this.money-=money;//从原来基础上,减去的钱
System.out.println(Thread.currentThread().getName()+"取了:"+money+",余额:"+this.money);
}
else {
System.out.println("屌丝没那么多存款,就别取这么多");
}
try {
wait();//如果运行了钱不够,就会停止运行,等待notify()的通知,有钱了,才会继续运行
}catch (InterruptedException e) {
e.printStackTrace();
}
}
}
机器操作
package test2022;
public class mybank implements Runnable {
private bank bk;
public mybank(bank bk) {
this.bk=bk;
}
public void run() {
for(int i=0;i<5;i++) {
bk.save(1000);//存1000
bk.take(1001);//取1001
bk.save(2);//存2
}
}
}
运行
package test2022;
public class qian {
public static void main(String[] args) {
bank b=new bank();
mybank m=new mybank(b);
Thread t=new Thread(m,"讷讷");
t.start();
}
}