1 package bytezero.threadtest2; 2 3 /** 4 * 银行有一个账户 5 * 有两个储户分别向同一个账户存 3000元,每次存1000,存三次,每次存完打印账户余额 6 * 7 * 分析: 8 * 1.是否是多线程的问题? 是,两个储户线程 9 * 2.是否有共享数据? 有 账户(或账户余额) 10 * 3.是否有线程安全问题? 有 11 * 4.需要考虑如何解决线程安全问题? 同步机制: 三种方式 12 * 13 * 14 * 15 * @author Bytezero1·zhenglei! Email:420498246@qq.com 16 * create 2021-10-18 11:49 17 */ 18 class Account{ 19 private double balance; 20 21 public Account(double balance) { 22 this.balance = balance; 23 } 24 //存钱 25 public synchronized void deposit(double amt){ 26 if(amt > 0){ 27 balance += amt; 28 29 try { 30 Thread.sleep(1000); 31 } catch (InterruptedException e) { 32 e.printStackTrace(); 33 } 34 System.out.println(Thread.currentThread().getName()+":存钱成功。余额为:"+balance); 35 } 36 } 37 38 } 39 class Customer extends Thread{ 40 private Account acct; 41 42 public Customer(Account acct) { 43 this.acct = acct; 44 } 45 46 @Override 47 public void run() { 48 for (int i = 0; i < 3; i++) { 49 acct.deposit(1000); 50 } 51 52 } 53 } 54 55 56 public class AccountTest { 57 public static void main(String[] args) { 58 Account acct = new Account(0); 59 60 Customer c1 = new Customer(acct); 61 Customer c2 = new Customer(acct); 62 63 c1.setName("甲"); 64 c2.setName("乙"); 65 66 c1.start(); 67 c2.start(); 68 } 69 70 }