1 package ltb20180106; 2 3 public class TestBankThread { 4 5 private int deposit=0;//注意全局变量的摆放. 6 7 public TestBankThread() { 8 9 10 } 11 12 13 14 class BankThread implements Runnable{ 15 16 17 18 public BankThread() { 19 20 21 } 22 23 public void setDeposit(int money) { 24 25 deposit+=money; 26 27 } 28 29 public int getMoney(int m) { 30 31 deposit=deposit-m; 32 33 if(deposit<0) { 34 35 System.out.println("ATM余额不足!!!"+deposit); 36 37 } 38 39 return m; 40 } 41 42 public int getBank() { 43 44 return deposit; 45 } 46 47 public void run() { 48 49 this.setDeposit(200); 50 51 System.out.println("ATM现有存款"+this.getBank()); 52 53 54 55 } 56 } 57 58 class A extends BankThread { 59 60 private int a=0; 61 62 public A() { 63 64 } 65 66 public void setA(int i) { 67 68 a=a+i; 69 } 70 71 public int getA() { 72 73 return a; 74 } 75 76 77 public void run() { 78 79 this.setA(super.getMoney(200)); 80 System.out.println("A从ATM取出:"+this.getA()); 81 System.out.println("ATM现在是"+this.getBank()); 82 this.setA(100); 83 System.out.println("在存入A100元最后是:"+a); 84 super.setDeposit(getA()); 85 System.out.println("存入ATM后:"+super.getBank()); 86 } 87 88 } 89 90 class B extends BankThread { 91 92 private int b=0;//余额 93 private int k=0;//取款数额 94 public B() { 95 96 } 97 98 public void setB(int i) { 99 100 b=b+i; 101 } 102 103 public int getB(int j) { 104 105 b=b-j; 106 107 if(j>b) { 108 109 System.out.println("类B:余额不足了"); 110 } 111 112 k=j; 113 114 return j; 115 } 116 117 public int getB() { 118 119 return b; 120 121 } 122 123 public int getK() { 124 125 return k; 126 } 127 128 public void run() { 129 130 this.setB(super.getMoney(300)); 131 System.out.println("B从ATM取走"+this.getB()+"元"); 132 this.getB(50); 133 super.setDeposit(this.getB()); 134 System.out.println("B取款"+this.getK()+"元,花掉了."); 135 System.out.println("ATM当前存款:"+super.getBank()); 136 137 } 138 139 140 141 } 142 143 public static void main(String[] args) { 144 145 TestBankThread tb=new TestBankThread(); 146 147 Thread t1=new Thread(tb.new BankThread()); 148 t1.start(); 149 Thread t2=new Thread(tb.new A()); 150 t2.start(); 151 Thread t3=new Thread(tb.new B()); 152 t3.start(); 153 154 } 155 156 }