package com.hao.javabasis.test.thread;
import java.math.BigDecimal;
/**
* @author haoxiansheng
* @date 2020-04-24
*/
public class AccountTest {
public static void main(String[] args) {
Account account = new Account(new BigDecimal(0));
Customer customerOne = new Customer(account);
Customer customerTwo = new Customer(account);
customerOne.setName("张三");
customerTwo.setName("李四");
customerOne.start();
customerTwo.start();
}
}
/**
* 分析
* 1、是否是多线程
* 2、是否有共享数据
* 3、如何解决 同步机制问题
*/
class Account {
private BigDecimal money;
public Account(BigDecimal money) {
this.money = money;
}
// 存钱
public synchronized void deposit(BigDecimal mon) {
if (mon.compareTo(new BigDecimal("0")) == 1) {
money = money.add(mon);
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName() + "存钱成功,余额为" + money);
}
}
}
class Customer extends Thread {
private Account account;
public Customer(Account account) {
this.account = account;
}
@Override
public void run() {
for (int i = 0; i < 3; i++) {
account.deposit(new BigDecimal(1000));
}
}
}