Java多线程导致的线程安全问题的实例解决
package m11.d20;
import java.util.Random;
/*
单用户同时存钱取钱的多线程解决线程安全问题解决的实例
*/
public class BankTest {
public static BankAccount acct=new BankAccount("张三",10000);
public static void main(String[] args) {
new Thread(new BankPutMoney()).start();
new Thread(new BankGetMoney()).start();
}
}
class BankAccount{
private static int init_id=1000;
private int id;
private double balance=0;
private String name="Jack";
public double succGetMoney=0;
public double succPutMoney=0;
public BankAccount(){
this.id=init_id++;
this.init();
}
public BankAccount( String name,double money ){
this.id=init_id++;
this.name=name;
this.balance=money;
this.init();
}
private void init(){
System.out.println("创建账户成功!当前账户ID为:"+this.id+",用户名为:"+this.name+",当前账户可用余额为"+this.balance+"元");
}
public void printBalance(){
System.out.println("账户:"+this.id+",可用余额为:"+this.balance+"元");
}
public synchronized void putMoney(double money){
this.balance+=money;
System.out.println("存款"+money+"元成功!账户:"+this.id+",用户余额为"+this.balance+"元");
BankTest.acct.succPutMoney+=money;
}
public synchronized void getMoney(double money){
if( this.balance-money<0 ){
System.out.println("取款失败!余额不足导致的失败交易!");
}else{
this.balance-=money;
System.out.println("取款成功!本次取款"+money+"元,当前可用余额为"+this.balance+"元");
BankTest.acct.succGetMoney+=money;
}
}
public double getBalance(){
return this.balance;
}
}
class BankPutMoney implements Runnable{
@Override
public void run() {
int i=0;
while (i<20){
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
BankTest.acct.putMoney((int)(Math.random()*5000+100));
i++;
}
System.out.println("所有存款操作完成,当前余额为"+BankTest.acct.getBalance()+"元");
System.out.println("截止当前,成功存款:"+BankTest.acct.succPutMoney+"元,成功取款:"+BankTest.acct.succGetMoney+"元");
}
}
class BankGetMoney implements Runnable{
@Override
public void run() {
int i=0;
while (i<20){
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
BankTest.acct.getMoney((int)(Math.random()*5000+100));
i++;
}
System.out.println("所有取款操作完成,当前余额为"+BankTest.acct.getBalance()+"元");
System.out.println("截止当前,成功存款:"+BankTest.acct.succPutMoney+"元,成功取款:"+BankTest.acct.succGetMoney+"元");
}
}
本作品采用 知识共享署名-相同方式共享 4.0 国际许可协议 进行许可。