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(); } }
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)