假设某家银行,它可接受顾客的汇款,每做一次汇款,便可计算出汇款的总额。现有两个顾客,每人都分3次,每次100元将钱到入。试编写一个程序,模拟实际作业
Bank.java
package com.lanqiao.demo8;
/**
* 银行 有一个累加的方法
* @author qichunlin
*
*/
public class Bank{
//总金额
private static int Count = 0;
public static void add(int n) {
int temp = Count;
temp+=n;
System.out.println(temp);
//Count=temp;
//System.out.println("金额为:"+Count);
try{
//Thread.sleep((Math.random()*10));
Thread.sleep((int)(10000*Math.random()));
}catch(InterruptedException e){
e.printStackTrace();
}
Count=temp;
System.out.println("金额为:"+Count);
}
}
Customer.java
package com.lanqiao.demo8;
/**
* Customer继承Thread 类 资源不共享
* @author qichunlin
*
*/
public class Customer extends Thread {
//获取名字
public Customer(String name) {
super(name);
}
@Override
public void run() {
for (int i = 0; i < 3; i++) {
System.out.print(this.getName() );
Bank.add(100);
}
}
}
Test.java
package com.lanqiao.demo8;
public class Test {
public static void main(String[] args) {
Customer c1 = new Customer("张三");
//启动线程
c1.start();//张三
Customer c2 = new Customer("李四");
c2.start();//李四
}
}