java程序设计基础_陈国君版第五版_第十一章习题

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


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值