java程序设计基础_陈国君版第五版_第十一章习题
/**
* 题目:假设某家银行可接受顾客的汇款,每进行一次汇款,便可计算出汇款的总额。现有两名顾客,每人分三次,每次一百元将钱汇入。试编程来模拟顾客的汇款操作。
* @author Richard-gao
*由题可知两名顾客可看成两个引用对同一个对象进行操作,同时两名顾客之间并不需要联系,所以这是两个线程。因此必须有同步的问题,不然容易出现阻塞后无法解决导致数据错误的结果。
*/
class MyBank{
private static int sum = 0;
public synchronized static void put(int k){
int temp = sum;
temp += k;
try{Thread.sleep((int)(1000*Math.random()));}
catch(InterruptedException e) {}
sum = temp;
System.out.println("总额:"+sum);
}
}
class Customer extends Thread
{
private String who;
public Customer(String who)
{
this.who = who;
}
public void run(){
for(int i = 0;i<3;i++){
MyBank.put(100);
}
}
}
public class Main11_8 {
public static void main(String[] args){
Customer c1 = new Customer("顾客1");
Customer c2 = new Customer("顾客2");
c1.start();
c2.start();
}
}