银行存款
假设某家银行,它可接受顾客的汇款,每做一次汇款,便可计算出汇款的总额。现有两个顾客,每人都分3次,每次100元将钱汇入。试编写一个程序,模拟实际作业。
程序如下:
classCBank
{ private static int sum=0;
public static void add(int n){
inttmp=sum;
tmp=tmp+n; // 累加汇款总额
try{
Thread.sleep((int)(10000*Math.random())); // 小睡几秒钟
}
catch(InterruptedException e){}
sum=tmp;
System.out.println("sum= "+sum);
}
}
class CCustomer extends Thread // CCustomer类,继承自Thread类
{ public void run(){ // run() method
for(inti=1;i<=3;i++)
CBank.add(100); // 将100元分三次汇入
}
}
public class Ex7_1
{ public static void main(String args[])
{ CCustomer c1=new CCustomer();
CCustomer c2=new CCustomer();
c1.start(); c2.start();
}
}
修改:加上 synchronized 关键字
package third;
class CBank {
public static int sum = 0;
public static synchronized void add(int n) {
int tmp = sum;
tmp = tmp + n; // 累加汇款总额
try {
Thread.sleep((int) (10000 * Math.random())); // 小睡几秒钟
} catch (InterruptedException e) {
}
sum = tmp;
System.out.println("sum= " + sum);
}
}
class CCustomer extends Thread // CCustomer类,继承自Thread类
{
public void run() { // run() method
for (int i = 1; i <= 3; i++)
CBank.add(100); // 将100元分三次汇入
}
}
public class test3 {
public static void main(String args[]) {
long start = System.currentTimeMillis();
long end;
CCustomer c1 = new CCustomer();
CCustomer c2 = new CCustomer();
c1.start();
c2.start();
}
}
|