急求助某JAVA程序中的三个小问题

来源:百度知道 编辑:UC知道 时间:2024/05/22 08:51:35
假设某家银行,它可接受顾客的汇款,每做一次汇款,便可计算出汇款的总额。现有两个顾客,每人都分3次,每次100元将钱到入。试编写一个程序,模拟实际作业。
程序如下:
class CBank
{
private static int sum=0;
public static 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 Ex6_1
{
public static void main(String args[])
{
CCustomer c1=new CCustomer();
CCustomer c2=new CCustomer();
c1.start();
c2.start();
}
}

①每次的运行结果和运行时间为什么会不同?
②要使程序运行结果每次相同,应该怎样修改程序?(要完整的)

class CBank {
private static int sum = 0;

public synchronized static 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);
}

public static void main(String args[]) {
CCustomer c1 = new CCustomer();
CCustomer c2 = new CCustomer();
c1.start();
c2.start();
}
}

class CCustomer extends Thread // CCustomer类,继承自Thread类
{
public void run() { // run() method
for (int i = 1; i <= 3; i++)
CBank.add(100); // 将100元分三次汇入
}
}

1. 和你的程序对比一下哪里不同?线程同步的关键问题之一就是共享资源(现在可以理解为变量或内存)的同步,记得在操作系统的课程里叫临界区吧,java已经让同步变的异常简单了--synchronized关键字

2. 虽然改好了,但是我觉的原来的程序更有意义,帮助我们理解为什么要同步/互斥

3. Well, you have to. Compiler force to do that.

家庭作业不可以这样偷