Java多线程银行取款

Java代码 复制代码  收藏代码
  1. package net.okren.java;   
  2.   
  3. import java.io.*;   
  4.   
  5. //账户   
  6. class Account{   
  7.     private float balance = 1000;   
  8.     public float getBalance(){   
  9.         return balance;   
  10.     }   
  11.        
  12.     public void setBalance(float balance){   
  13.         this.balance = balance;   
  14.     }   
  15.        
  16.     public synchronized void withDraw(float money){   
  17.         if(balance >= money){   
  18.             System.out.println("取走 "+ money +"钱");   
  19.             try{   
  20.                 Thread.sleep(1000);   
  21.             }catch(InterruptedException e){   
  22.                 e.printStackTrace();   
  23.             }   
  24.             balance -= money;   
  25.         }else{   
  26.             System.out.println("余额不足 ");   
  27.         }   
  28.     }   
  29. }   
  30.   
  31. class TestAccount1 extends Thread{   
  32.     private Account account;   
  33.     public TestAccount1(Account account){   
  34.         this.account = account;   
  35.     }   
  36.        
  37.     public void run(){   
  38.         account.withDraw(800);   
  39.         System.out.println("余额为"+ account.getBalance());   
  40.     }   
  41. }   
  42.   
  43. class TestAccount2 extends Thread{   
  44.     private Account account;   
  45.     public TestAccount2(Account account){   
  46.         this.account = account;   
  47.     }   
  48.        
  49.     public void run(){   
  50.         account.withDraw(700);   
  51.         System.out.println("余额为 " + account.getBalance());   
  52.     }   
  53. }   
  54. public class JavaTest {   
  55.        
  56.     public static void main(String[] args){   
  57.            
  58.         Account account = new Account();   
  59.         TestAccount1 t1 = new TestAccount1(account);   
  60.         TestAccount2 t2 = new TestAccount2(account);   
  61.         t1.start();   
  62.         t2.start();   
  63.        
  64.            
  65.     }   
  66. }  
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值