Java多线程同步学习 取款例子
/** * 线程同步学习 * @author Administrator * */ public class Crow_Thread { /** * 测试 */ public static void main(String[] args) { //例如张三的用户 Account account = new Account(); //张三的姐姐拥有张三的银行用户 Thread t1 = new Thread(new Bank1(account)); //张三的哥哥拥有张三的银行用户 Thread t2 = new Thread(new Bank2(account)); //张三的姐姐去取钱 t1.start(); //张三的哥哥去取钱 t2.start(); } } /** * 账户 * @author Administrator * */ class Account{ private float money = 1000f; public float getMoney() { return money; } public void setMoney(float money) { this.money = money; } /** * synchronized<---设置同步 * @param price */ public synchronized void putMoney(float price){ if(money>=price){ try { Thread.sleep(1000); } catch (Exception e) { // TODO: handle exception } System.out.println("被取走"+price+"元"); money-=price; }else{ System.out.println("当前余额不足,剩下:"+money+"元"); } } } /** * 柜台1 * @author Administrator * */ class Bank1 implements Runnable{ private Account account; public Account getAccount() { return account; } public void setAccount(Account account) { this.account = account; } public Bank1(Account account) { super(); this.account = account; } @Override public void run() { System.out.println("从银行1来取:"+800+"块钱"); //柜台2想去取走800块钱 account.putMoney(800); System.out.println("剩余:"+account.getMoney()); } } /** * 柜台2 * @author Administrator * */ class Bank2 implements Runnable{ private Account account; public Account getAccount() { return account; } public void setAccount(Account account) { this.account = account; } public Bank2(Account account) { super(); this.account = account; } @Override public void run() { System.out.println("从银行2来取:"+700+"块钱"); //柜台2想去取走700块钱 account.putMoney(700); System.out.println("剩余:"+account.getMoney()); } }
输出的是
从银行1来取:800块钱
从银行2来取:700块钱
被取走800.0元
剩余:200.0
当前余额不足,剩下:200.0元
剩余:200.0
如果不在取钱方法加 synchronized 关键字
输出的是
从银行1来取:800块钱
从银行2来取:700块钱
被取走800.0元
剩余:200.0
被取走700.0元
剩余:-500.0

浙公网安备 33010602011771号