package com.li.thread_synchronized;
//不安全取钱
public class UnsafeWithdrawMoney {
public static void main(String[] args) {
//账户
Account account = new Account("结婚基金",100);
//取钱
WithdrawMoney me = new WithdrawMoney(account,50);
WithdrawMoney wife = new WithdrawMoney(account,100);
new Thread(me,"我").start();
new Thread(wife,"妻子").start();
}
}
//账户
class Account {
String name;//账户名
int money;//卡余额
public Account(String name, int money) {
this.name = name;
this.money = money;
}
}
//模拟银行取款
class WithdrawMoney implements Runnable{
Account account;//账户
int withdrawMoney;//取的钱
public WithdrawMoney(Account account, int withdrawMoney) {
this.account = account;
this.withdrawMoney = withdrawMoney;
}
//取钱
@Override
public void run() {
//判断账户有没有钱
if (account.money-withdrawMoney<0) {
System.out.println(Thread.currentThread().getName() + ",账户余额不足,取不了,余额为:" + account.money);
return;
}
//模拟延时
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
//卡余额 = 余额 - 取的钱
account.money = account.money - withdrawMoney;
System.out.println(account.name + "余额:" + account.money);
System.out.println(Thread.currentThread().getName()+ "取了:" + withdrawMoney);
}
}
Java零基础学java之多线程--16线程不安全案例02
最新推荐文章于 2024-10-01 09:29:45 发布