Java(妻取钱丈夫花钱

本文介绍了一个Java并发编程的简单例子,通过`Husband`和`Wife`类模拟丈夫和妻子对共享`ShareBank`账户的操作,包括存款和取款,使用`synchronized`关键字保证线程安全。
摘要由CSDN通过智能技术生成
package Thread;

public class Test1 {
    public static void main(String[] args) {

        ShareBank account = new ShareBank();
        Husband husband = new Husband(account, 100); // 假设丈夫每天收入100元
        Wife wife = new Wife(account, 50, 200); // 假设妻子每次消费在50元到200元之间
        husband.start();
        wife.start();
    }
}
package Thread;

public class ShareBank {
    private double balance;//共享账户

    // 存款方法
    public synchronized void deposit(int amount) {
        balance += amount;
        System.out.println("存款成功,当前余额:" + balance);
    }

    // 取款方法
    public synchronized void withdraw(int amount) {
        if (balance >= amount) {
            balance -= amount;
            System.out.println("取款成功,当前余额:" + balance);
        } else {

        }
    }
}
package Thread;

import java.util.Random;

public class Husband extends Thread {
    private ShareBank account;
    private int income;
    Random r=new Random();
    public Husband(ShareBank account, int income) {
        this.account = account;
        this.income = income;
    }

    @Override
    public void run() {
        while (true) {
            account.deposit(income);
            try {
                Thread.sleep(r.nextInt(10000));
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}
package Thread;

import java.util.Random;

public class Wife extends Thread{
    private ShareBank account;
    private int min;
    private int max;
    Random r=new Random();

    public Wife(ShareBank account, int min, int max) {
        this.account = account;
        this.min = min;
        this.max = max;
    }

    @Override
    public void run() {
        while (true) {
            int ds=min+r.nextInt(max-min);
            account.withdraw(ds);
            try {
                Thread.sleep(r.nextInt(10000));
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}

 

 如果想规定天数,需要设置一个静态变量day,然后进行判断结束循环,我这个代码是没结束的;

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值