首页 > 技术文章 > java多线程 银行取款

pinksnow520 2014-11-26 11:35 原文

  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. }  

推荐阅读