Java 并发控制实例 (银行问题取钱存钱)

并发主要的就是解决同步问题。

如果数据不同步,如假设A的银行余额为500。A用网银取了500,同时用ATM机取了500,那A将会有概率总共取得1000(因为网银与ATM是独立的,出现网银取钱了,但还未扣款,或者扣了钱但数据还没反馈到总服务器,然后ATM的得的数据还是原来的数据,即余额任然为500,所以依然可以取出500,500+500=1000).

所以需要并发控制来解决问题,此实例采用Java 中 的 synchroniezd实现同步

package com.asmn.bank;

import static com.asmn.tools.Tools.*;

public class Main {
	public static void main(String[] args) {
		//初始余额为500
		Bank bank = new Bank(500);
		char []names = "ABCDEF".toCharArray();
		for(char name : names){
			new Thread(new reduce(bank,name,50)).start();
		}
		for(char name : names){
			new Thread(new Add(bank,name,50)).start();
		}
	}
}

class Add implements Runnable {
	private Bank bank;
	private int sum;
	private char name;
	
	public Add(Bank bank, char name, int sum){
		this.bank = bank;
		this.sum = sum;
		this.name = name;
	}
	
	@Override
	public void run() {
		try {
			bank.add("加"+name, sum);
			Thread.sleep(500);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
	}
}

class reduce implements Runnable {
	private Bank bank;
	private int sum;
	private char name;
	
	public reduce(Bank bank, char name, int sum){
		this.bank = bank;
		this.sum = sum;
		this.name = name;
	}
	
	@Override
	public void run() {
		try {
			bank.reduce("减"+name,sum);
			Thread.sleep(500);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
	}
}
package com.asmn.bank;

import static com.asmn.tools.Tools.*;

public class Bank {
	private int money = 0;
	
	public Bank(int money){
		this.money = money;
	}
	
	public synchronized int getMoney(){
		return money;
	}
	
	public synchronized void add(String name, int sum){
		money += sum;
		pl(name+"加了"+sum+",剩余"+money);
	}
	
	public synchronized boolean reduce(String name, int sum){
		if(sum > money){
			pl("钱不够扣");
			return false;
		}
		
		
		money -= sum;
		pl(name+"剪了"+sum+",剩余"+money);
		return true;
	}
	
}

可将Bank类中的synchronized关键字删除和不删除进行比较输出结果

APP、软件、网站开发可以在下方评论处留言

你可能感兴趣的:(JAVA)