西农大 Java实习 实验5 多线程 第三题

西农大 Java实习 实验5 多线程 第三题,第1张

西农大 Java实习 实验5 多线程 第三题

银行存款

假设某家银行,它可接受顾客的汇款,每做一次汇款,便可计算出汇款的总额。现有两个顾客,每人都分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();
	}
}

欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/zaji/5522486.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-12-13
下一篇 2022-12-13

发表评论

登录后才能评论

评论列表(0条)

保存