public class Account {
//账户金额
private int amount;
public Account(int amount){
this.amount = amount;
}
//转账
public synchronized void trans(Account to,int value){
//条件判断处于同步代码中!!!!!!
if(amount - value < 0){
throw new RuntimeException("钱不够了!");
}
this.amount -= value;
to.addAmount(value);
System.out.println("转账成功");
}
public void addAmount(int amount){
this.amount += amount;
}
public int getAmount(){
return this.amount;
}
public static void main(String[] args) {
Account from = new Account(100);
Account to1 = new Account(0);
Account to2 = new Account(0);
List<CompletableFuture> cfs = new ArrayList<>();
cfs.add(CompletableFuture.runAsync(() -> from.trans(to1,100)));
cfs.add(CompletableFuture.runAsync(() -> from.trans(to2,100)));
CompletableFuture.allOf(cfs.toArray(new CompletableFuture[cfs.size()])).join();
System.out.println(from.getAmount());
System.out.println(to1.getAmount());
System.out.println(to2.getAmount());
}
}