import java.util.Random;
public class ExerciseMoney {
public static void main(String[] args) throws InterruptedException {
Account account1 = new Account(10000);
Account account2 = new Account(10000);
Thread thread1 = new Thread(()->{
for (int i = 0; i < 1000; i++) {
account1.transfer(account2,randomAmount());
}
},"thread1");
Thread thread2 = new Thread(()->{
account2.transfer(account1,randomAmount());
});
thread1.start();
thread2.start();
thread1.join();
thread2.join();
System.out.println("查看两个账户的总金额:" + (account1.getMoney() + account2.getMoney()));
}
static Random random = new Random();
public static int randomAmount(){
return random.nextInt(100) + 1;
}
}
class Account{
private int money;
public Account(int money) {
this.money = money;
}
public int getMoney() {
return money;
}
public void setMoney(int money) {
this.money = money;
}
public void transfer(Account target, int amount){
synchronized (Account.class) {
if (this.money >= amount) {
this.setMoney(this.getMoney() - amount);
target.setMoney(target.getMoney() + amount);
}
}
}
}