您好,登录后才能下订单哦!
密码登录
登录注册
点击 登录注册 即表示同意《亿速云用户服务条款》
这篇文章给大家分享的是有关Java实现银行存取款的方法的内容。小编觉得挺实用的,因此分享给大家做个参考,一起跟随小编过来看看吧。
具体内容如下
1.不加锁情况
运行结果:
代码:将加锁情况中加锁部分进行注释即可
2.加锁情况
运行结果
缓冲区代码
package Bank; import java.util.LinkedList; public class BankAccount { static double sum=1000; private LinkedList<Object> list = new LinkedList<>(); //存款 public void deposit() { synchronized(list) { System.out.print(list.size()); while(list.size()>1) { System.out.println("暂不支持存款"); try { // System.out.print("wait"); list.wait(); } catch (InterruptedException e) { e.printStackTrace(); //System.out.print("wait"); } } list.add(new Object()); int money=300; sum=sum+money; System.out.println(Thread.currentThread().getName()+"存入了"+money+"元"+"现在共有存款"+sum); list.notifyAll(); } } //取款 public void withdrawal() { synchronized(list) { while(list.size()==0) { // int money=50; // sum=sum-money; System.out.println(Thread.currentThread().getName()+"暂时不支持取款"); try { list.wait(); } catch (InterruptedException e) { e.printStackTrace(); } } list.remove(); int money=200; if(sum>200) { sum=sum-money; System.out.println(Thread.currentThread().getName()+"取出了"+money+"元"+"现在共有存款"+sum); }else { System.out.println("账户余额不足"); } list.notify(); } } }
存款代码
package Bank; public class Deposit implements Runnable { private BankAccount bankAccount1; public Deposit() {} public Deposit(BankAccount bankAccount1) { this.bankAccount1=bankAccount1; } @Override public void run() { // TODO Auto-generated method stub while(true) { try { Thread.sleep(2000); bankAccount1.deposit(); } catch (InterruptedException e) { // TODO: handle exception e.printStackTrace(); } } } }
取款代码
package Bank; public class Withdrawal implements Runnable{ private BankAccount bankAccount; public Withdrawal() {} public Withdrawal(BankAccount bankAccount) { this.bankAccount=bankAccount; } @Override public void run() { // TODO Auto-generated method stub while(true) { try { Thread.sleep(3000); bankAccount.withdrawal(); } catch (InterruptedException e) { // TODO: handle exception e.printStackTrace(); } } } }
主函数代码
package Bank; public class Main { public static void main(String[] args) { BankAccount bankAccount1=new BankAccount(); Thread d1=new Thread(new Deposit(bankAccount1)); Thread d2=new Thread(new Deposit(bankAccount1)); Thread d3=new Thread(new Deposit(bankAccount1)); Thread w1=new Thread(new Withdrawal(bankAccount1)); Thread w2=new Thread(new Withdrawal(bankAccount1)); Thread w3=new Thread(new Withdrawal(bankAccount1)); d1.start(); d2.start(); d3.start(); w1.start(); w2.start(); w3.start(); } }
感谢各位的阅读!关于“Java实现银行存取款的方法”这篇文章就分享到这里了,希望以上内容可以对大家有一定的帮助,让大家可以学到更多知识,如果觉得文章不错,可以把它分享出去让更多的人看到吧!
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。