2、模拟一个银行存款的程序。假设有三个储户都去银行往同一个账户进行存款,一次存100,每人存三次。要求储户每存一次钱,账户余额增加100,并在控制台输出当前账户的余额。
package com;
class Bank {
private int money=0;
public void deposits(){
money+=100;
}
public String toString() {
return "\t余额:"+money+"元";
}
public int getMoney() {
return money;
}
public void setMoney(int money) {
this.money = money;
}
}
class user implements Runnable {
Bank bank = new Bank();
public void run(){
int num = 0;
while(num <3){
num++;
synchronized(this){
bank.deposits();
System.out.println( Thread.currentThread().getName()
+ "正在"+(num)+"次存100元"+ bank.toString());
}
}
}
}
public class Test {
public static void main(String[] args) {
user user = new user();
new Thread(user,"用户A").start();
new Thread(user,"用户B").start();
new Thread(user,"用户C").start();
}
}