转账练习 测试下面代码是否存在线程安全问题,并尝试改正
1 package cn.itcast.n4.exercise; 2 3 import lombok.extern.slf4j.Slf4j; 4 5 import java.util.Random; 6 7 @Slf4j(topic = "c.ExerciseTransfer") 8 public class ExerciseTransfer { 9 public static void main(String[] args) throws InterruptedException { 10 Account a = new Account(1000); 11 Account b = new Account(1000); 12 Thread t1 = new Thread(() -> { 13 for (int i = 0; i < 1000; i++) { 14 a.transfer(b, randomAmount()); 15 } 16 }, "t1"); 17 Thread t2 = new Thread(() -> { 18 for (int i = 0; i < 1000; i++) { 19 b.transfer(a, randomAmount()); 20 } 21 }, "t2"); 22 t1.start(); 23 t2.start(); 24 t1.join(); 25 t2.join(); 26 // 查看转账2000次后的总金额 27 log.debug("total:{}", (a.getMoney() + b.getMoney())); 28 } 29 30 // Random 为线程安全 31 static Random random = new Random(); 32 33 // 随机 1~100 34 public static int randomAmount() { 35 return random.nextInt(100) + 1; 36 } 37 } 38 39 // 账户 40 class Account { 41 private int money; 42 43 public Account(int money) { 44 this.money = money; 45 } 46 47 public int getMoney() { 48 return money; 49 } 50 51 public void setMoney(int money) { 52 this.money = money; 53 } 54 55 // 转账 56 public void transfer(Account target, int amount) { 57 58 if (this.money >= amount) { 59 this.setMoney(this.getMoney() - amount); 60 target.setMoney(target.getMoney() + amount); 61 } 62 } 63 }

出现的问题在这:

更正代码:

                    
                
                
            
        
浙公网安备 33010602011771号