钱的数量要设置成一个静态的变量。两个人要取的同一个对象值
import java.util.Random;
import java.util.concurrent.atomic.AtomicInteger;
/**
* @Author: 张
* @Date: 2019/2/11 15:00
* @Version: 1.0
* @Description: 1.0
*/
public class BankTest {
public static class Account {
private AtomicInteger amount;
private String name;
public void name() {
System.out.println("账户为:" + name + "!");
}
public boolean deposit(String threadName, int change) {
amount.addAndGet(change);
if (amount.get() > 2000) {
System.out.print("存款金额已经达到上限,存款失败");
return false;
}
System.out.println("01:" + threadName + "开始存款,存款后余额为" + amount);
return true;
}
public boolean withdraw(String threadName, int money) {
if (amount.get() <= 0 || amount.get() < money) {
System.out.println("账户金额小于0,取款失败");
return false;
} else {
amount.addAndGet(-money);
System.out.println("02:" + threadName + "开始取款,取款后余额为" + amount);
return true;
}
}
public void openAccount(String name, Integer money) {
this.name = name;
this.amount = new AtomicInteger(money);
System.out.println(name + "开户成功!");
}
}
public static class PersonDeposit implements Runnable {
private Account account;
private int deposit;
public void deposit(Account account, int deposit) {
this.account = account;
this.deposit = deposit;
}
@Override
public void run() {
String threadName = Thread.currentThread().getName();
while (true) {
if (account.amount.get() < 2000) {
boolean isFlag = account.deposit(threadName, deposit);
if (!isFlag) {
break;
}
try {
Thread.sleep(new Random().nextInt(1000));
} catch (InterruptedException e) {
e.printStackTrace();
}
} else {
break;
}
}
}
}
public static class PersonWithdraw implements Runnable {
private Account account;
private int withdraw;
public void withdraw(Account account, int withdraw) {
this.account = account;
this.withdraw = withdraw;
}
@Override
public void run() {
String threadName = Thread.currentThread().getName();
while (true) {
if (account.amount.get() > 0) {
boolean isFlag = account.withdraw(threadName, withdraw);
if (!isFlag) {
break;
}
try {
Thread.sleep(new Random().nextInt(1000));
} catch (InterruptedException e) {
e.printStackTrace();
}
} else {
break;
}
}
}
}
public static void main(String[] args) {
Account account = new Account();
account.openAccount("张小乙", 1000);
PersonDeposit p1 = new PersonDeposit();
p1.deposit(account, 50);
Thread depositThread = new Thread(p1, "张三");
PersonWithdraw p2 = new PersonWithdraw();
p2.withdraw(account, 99);
Thread withdrawThread = new Thread(p2, "李四");
depositThread.start();
withdrawThread.start();
}
}
例子来源于戳戳我