栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

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

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

西农大 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();
	}
}

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/530638.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号