Java多线程竞态条件代码示范

《JAVA核心技术 卷一》例题12-3

输出结果:

可以观察到多线程竞争后,出现总金额少于100000的情况
可以观察到多线程竞争后,出现总金额尽然少于100000的情况

代码示例

创建Bank类

public class Bank {
	private final double[] accounts;
	
	public Bank(int n, double initialBalance) {
		accounts = new double[n];
		// 将initialBalance中的数分给accounts数组中的每一个元素。
		Arrays.fill(accounts,initialBalance);
	}
	
	// 设置账户转移,从from账户,转移到to账户。
	public void transfer(int from, int to, double amount) {
		// 当from账户的钱小于随机数amount时跳出,因为钱不够转了嘛。
		if(accounts[from] < amount) return;
		// Thread.currentThread():返回当前正在执行的线程
		System.out.print(Thread.currentThread());
		// 转钱随机数amount给to账户
		accounts[from] -= amount;
		System.out.printf(" %10.2f from %d to %d",amount ,from,to);
		accounts[to] += amount;
		System.out.printf(" Total Balance:%10.2f%n",getTotalBalance());
	}

	private double getTotalBalance() {
		double sum = 0;
		for(double a : accounts) {
			sum += a;
		}
		return sum;
	}
	
	public int size() {
		return accounts.length;
	}
}

创建主类

public class RaceTest_Bank {
	public static final int NACCOUNTS = 100; 
	public static final double INITIAL_BALANCE = 1000;  
	public static final int DELAY = 100;
	public static final double MAX_AMOUNT = 1000;
	
	public static void main (String[] gars) {
		// 创建100个账户,每个账户分配1000元
		Bank bank = new Bank(NACCOUNTS,INITIAL_BALANCE);
		
		for(int i = 0; i < NACCOUNTS; i++) {
			int fromAccount = i;
			Runnable r = ()->{
				try {
					while(true){
						int toAccount = (int)(bank.size() * Math.random());
						double amount = MAX_AMOUNT * Math.random();  // amount = 1000*随机数 
						bank.transfer(fromAccount, toAccount, amount);
						// 设置随机休眠
						Thread.sleep((int)(DELAY * Math.random()));
					}
				}
				catch (InterruptedException e) {
				}
			}; 
			Thread t = new Thread(r);
			t.start();
		}
	}
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值