package com.stu.bankModel;
/**
* 线程安全测试
* 通过存取钱案列检验
* @author jj
*
*/
public class ThreadSafeTest {
public static void main(String[] args) {
Account account = new Account("张山", 5000D);
DrawOperation draw = new DrawOperation(account, 1000D);
for(int i=0;i<50;i++){
new Thread(draw).start();
}
SaveOperation save = new SaveOperation(account, 500D);
for(int i=0;i<50;i++){
new Thread(save).start();
}
}
}
/**
* 账户类
* @author jj
*
*/
class Account{
private String name;
private Double balance;
public Account(String name, Double balance) {
super();
this.name = name;
this.balance = balance;
}
public Account() {
super();
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Double getBalance() {
return balance;
}
public void setBalance(Double balance) {
this.balance = balance;
}
/**
* 存钱
*/
public void Save(Double money){
this.balance = this.balance + money;
System.out.println(this.name + "存入金额:" +money+"\t余额:"+this.balance);
}
/**
* 取钱
*/
public void Draw(Double money){
if(this.balance>=money){
this.balance = this.balance - money;
System.out.println(this.name + "取款金额:" +money+"\t余额:"+this.balance);
}else{
System.out.println("余额不足!当前余额:"+this.balance);
}
}
}
/**
* 账户操作类(取款)
* @author jj
*
*/
class DrawOperation implements Runnable{
private Account account;//账户
private Double drawMoney;//取款金额
public DrawOperation(Account account, Double drawMoney){
this.account = account;
this.drawMoney = drawMoney;
}
@Override
public void run() {
synchronized(account){
try {
account.Draw(drawMoney);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
/**
* 存款操作
* @author jj
*
*/
class SaveOperation implements Runnable{
private Account account;
private Double saveMoney;
public SaveOperation(Account account, Double saveMoney){
this.account = account;
this.saveMoney = saveMoney;
}
@Override
public void run() {
// TODO Auto-generated method stub
synchronized (account) {
try {
account.Save(saveMoney);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
推荐一篇关于关键字synchronized的博客:
https://blog.csdn.net/luoweifu/article/details/46613015
java实现存取钱过程(synchronized关键字的应用)
最新推荐文章于 2022-03-03 08:49:03 发布