package MultiThreadTest;
import java.math.BigDecimal;
/**
* @author 苏雪夜酒
* @version 1.0
* @date 2021/10/24 22:11
* 因为是对同一个类的不同对象 故
* synchronized (Account.class)
*/
public class Account {
//变量
private BigDecimal money;
//无参构造方法
public Account() {
}
//有参构造方法
public Account(BigDecimal money) {
this.money = money;
}
//get 方法
public BigDecimal getMoney() {
return money;
}
//set 方法
public void setMoney(BigDecimal money) {
this.money = money;
}
//成员方法 转账
public void transfer(Account targetAccount, BigDecimal amount){
synchronized (Account.class){
if (this.money.compareTo(amount) > 0 ){
this.setMoney(this.getMoney().subtract(amount));
targetAccount.setMoney(targetAccount.getMoney().add(amount));
}
}
}
}
package MultiThreadTest;
import java.math.BigDecimal;
import java.util.Random;
/**
* @author 苏雪夜酒
* @version 1.0
* @date 2021/10/24 22:18
*/
public class TransferMoneyThread {
public static void main(String[] args) throws InterruptedException {
Account account1 = new Account(new BigDecimal(10000));
Account account2 = new Account(new BigDecimal(10000));
Thread thread1 = new Thread(()->{
for (int i = 0; i < 10; i++) {
account1.transfer(account2,randomAmount());
}
},"thread1");
Thread thread2 = new Thread(()->{
for (int i = 0; i < 10; i++) {
account1.transfer(account2,randomAmount());
}
},"thread2");
//start()启动线程
thread1.start();
thread2.start();
//等待一个线程结束后,另一个线程再启动
thread1.join();
thread2.join();
System.out.println("account1的账户金额:" + account1.getMoney());
System.out.println("account2的账户金额:" + account2.getMoney());
System.out.println("两个账户的总金额:" + account1.getMoney().add(account2.getMoney()));
}
static Random random = new Random();
public static BigDecimal randomAmount(){
return new BigDecimal(random.nextDouble());
}
}