题目描述:
Wife线程类,负责花钱1万的随机整数倍,每次不超过10万,
如果余额不够但不为0,则有多少就花多少,没钱就wait;
Husband线程类,负责赚钱,2万的随机整数倍,每次不超过10万;
如果余额超过10万(含),则wait;如果余额加上新赚的钱超过10万,
则保留(例如余额5万,新赚6万,则新余额11万)
Account钱类(属性:int money,下限0万元)
TestMoney场景类,启动一个Husband线程,启动两个Wife线程,
模拟老公赚钱,老婆花钱的过程.
import java.util.concurrent.Executors;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
public class practice05 {
private static Account account = new Account();
private static class Account{
//账户余额
private int balance;
private Lock lock = new ReentrantLock(true);
//存款
private Condition deposit = lock.newCondition();
public void setBalance(int balance){
this.balance = balance;
}
//Husband线程类(存钱)
public void Husband(int amount){
try {
lock.lock();
while (balance + amount < 10){
balance += amount;
System.out.println("Husband存入金额:" + amount + " ,当前余额:" + balance);
//只要存入钱就尝试唤醒Wife(取钱)线程
deposit.signal();
}
} catch (Exception e) {
throw new RuntimeException(e);
} finally {
lock.unlock();//释放锁
}
}
public void Wife(int amount){
try {
lock.lock();
if(amount > balance && balance > 0){
System.out.println("虽然想花:" + amount + "元,但存款只有:" + balance + ",花掉:" + balance);
balance -= balance;
}else if(balance == 0){
System.out.println("余额不足,等待Husband存款");
deposit.await();
}else{
balance -= amount;
System.out.println("Wife取款:" + amount + ",当前余额:" + balance);
}
} catch (InterruptedException e) {
throw new RuntimeException(e);
} finally {
lock.unlock();
}
}
}
//Husband(存款)线程
private static class HusbandTask implements Runnable{
@Override
public void run() {
try {
while(true){
account.Husband((int) (Math.random() * 5) * 2 + 2);
//线程休眠1秒
Thread.sleep(1000);
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
//Wife(取款)任务线程
private static class WifeTask implements Runnable{
@Override
public void run() {
try {
while (true){
account.Wife((int) (Math.random() * 10) + 1);
//线程休眠1秒
Thread.sleep(1000);
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
//主函数调用执行线程
public static void main(String[] args) {
var executor = Executors.newFixedThreadPool(3);
//一个Husband线程存钱
executor.execute(new HusbandTask());
//两个Wife线程花钱
executor.execute(new WifeTask());
executor.execute(new WifeTask());
//线程关闭
executor.shutdown();
}
}