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

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

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

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

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

输出结果:

可以观察到多线程竞争后,出现总金额少于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();
		}
	}
}
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/782620.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

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

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