银行存取款多线程

银行存取款多线程,第1张

银行存取款多线程
import java.util.Random;
import java.lang.*;

public class Bank {
    private int count = 0;

    
    public synchronized void addMoney(int money) {
        count += money;
        System.out.print("在"+Thread.currentThread().getName()+"上存" + money);
    }

    
    public synchronized void getMoney(int money){

            if (count >= money) {

                    count -= money;
                    System.out.print("在" + Thread.currentThread().getName() + "取" + money);

            }else {
                System.out.print("余额不足");
            }

    }

    
    public synchronized void show(){

            System.out.println(",余额为"+count);


    }
}
class getMoney implements Runnable{
    // Bank对象
    private Bank bank;
    // 取钱数
    private int money;

    
    public getMoney(Bank bank,int money){
        this.bank = bank;
        this.money = money;
    }
    @Override
    public void run() {
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        synchronized (this){
            bank.getMoney(money);
            bank.show();
        }


    }
}
class saveMoney implements Runnable{
    private Bank bank;
    private int money;
    
    public saveMoney(Bank bank,int money){
        this.bank = bank;
        this.money = money;
    }
    @Override
    public void run() {
        for (int i = 0; i < 10; i++) {
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            synchronized (this){
                bank.addMoney(money);
                bank.show();
            }
        }

    }
}
class Test{
    public static void main(String[] args) {
        Bank bank = new Bank();
        // ATM存钱
        Thread t1 = new Thread(new saveMoney(bank,new Random().nextInt(100)),"ATM");
        // ATM取钱
        Thread t2 = new Thread(new getMoney(bank,new Random().nextInt(100)),"ATM");
        // 银行柜台存钱
        Thread t3 = new Thread(new saveMoney(bank,new Random().nextInt(100)),"银行柜台");
        // 银行柜台取钱
        Thread t4 = new Thread(new getMoney(bank,new Random().nextInt(100)),"银行柜台");
        t1.start();
        t2.start();
        t3.start();
        t4.start();
    }
}

欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/zaji/5682522.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-12-17
下一篇 2022-12-17

发表评论

登录后才能评论

评论列表(0条)

保存