Today, my classmates asked about bank deposits and withdrawals, how to keep synchronization, and wrote a simple example.
First is the bank:
private int money = 1000;
public synchronized void add(int n) {
money += n;
try {
Thread.sleep(1000);
} catch (Exception e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName() + "----余额: " + money);
}
public synchronized void reduce(int n) {
if(money - n >= 0) {
money -= n;
} else {
System.out.println("余额不足");
}
try {
Thread.sleep(1000);
} catch (Exception e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName() + "----余额: " + money);
}
The key is method locking, which uses the built-in mutex lock mechanism of java.
Next is the user:
public Bank bank;
static final String TYPE_ADD = "add";
static final String TYPE_REDUCE = "reduce";
private String type;
private int time;
private int money;
public Customer() {
}
public Customer(Bank bank, String type, int time, int money) {
this.bank = bank;
this.type = type;
this.time = time;
this.money = money;
}
@Override
public void run() {
for(int i = 0; i < time; i++) {
if (TYPE_ADD.equals(type)) {
bank.add(money);
} else if (TYPE_REDUCE.equals(type)) {
bank.reduce(money);
}
}
}
And finally the test class:
Bank bank = new Bank();
Customer a1 = new Customer(bank, Customer.TYPE_ADD, 10, 100);
Customer a2 = new Customer(bank, Customer.TYPE_REDUCE, 10, 100);
Thread t1 = new Thread(a1);
Thread t2 = new Thread(a2);
t1.start();
t2.start();