使用synchronized同步,经典银行账户问题
1.新建Account类,使用synchronized同步增加和减少金额方法。
package com.xkzhangsan.synchronizedpack.bank; public class Account { private double balance; public synchronized void addAmount(double amount){ double tmp = balance; try { Thread.sleep(10); } catch (InterruptedException e) { e.printStackTrace(); } tmp+=amount; balance=tmp; } public synchronized void substractAmount(double amount){ double tmp = balance; try { Thread.sleep(10); } catch (InterruptedException e) { e.printStackTrace(); } tmp-=amount; balance=tmp; } public double getBalance() { return balance; } public void setBalance(double balance) { this.balance = balance; } }
2.新建Company类,往账户增加金额,实现Runnable接口
package com.xkzhangsan.synchronizedpack.bank; public class Company implements Runnable{ private Account account; public Company(Account account) { super(); this.account = account; } public void run() { for (int i = 0; i < 10; i++) { account.addAmount(1000); System.out.println("Company add 1000 balance:" + account.getBalance()); } } }
3.新建Bank类,减少账户金额,实现Runnable接口
package com.xkzhangsan.synchronizedpack.bank; public class Bank implements Runnable{ private Account account; public Bank(Account account) { super(); this.account = account; } public void run() { for (int i = 0; i < 10; i++) { account.substractAmount(1000); System.out.println("Bank substract 1000 balance:" + account.getBalance()); } } }
4.新建Main测试类,创建companyThread和bankThread,启动线程,打印账户金额变化
package com.xkzhangsan.synchronizedpack.bank; public class Main { public static void main(String[] args) { Account account = new Account(); account.setBalance(1000); Company company = new Company(account); Thread companyThread = new Thread(company); Bank bank = new Bank(account); Thread bankThread = new Thread(bank); System.out.printf("Account start money:%f\n", account.getBalance()); companyThread.start(); bankThread.start(); try { companyThread.join(); bankThread.join(); System.out.printf("Account end money:%f\n", account.getBalance()); } catch (InterruptedException e) { e.printStackTrace(); } } }
5.测试结果
Account start money:1000.000000
Company add 1000 balance:2000.0
Bank substract 1000 balance:1000.0
Company add 1000 balance:2000.0
Bank substract 1000 balance:1000.0
Company add 1000 balance:2000.0
Bank substract 1000 balance:1000.0
Company add 1000 balance:2000.0
Bank substract 1000 balance:1000.0
Company add 1000 balance:2000.0
Bank substract 1000 balance:1000.0
Company add 1000 balance:2000.0
Bank substract 1000 balance:1000.0
Company add 1000 balance:2000.0
Bank substract 1000 balance:1000.0
Company add 1000 balance:2000.0
Bank substract 1000 balance:1000.0
Company add 1000 balance:2000.0
Bank substract 1000 balance:1000.0
Company add 1000 balance:2000.0
Bank substract 1000 balance:1000.0
Account end money:1000.000000
参考:java7并发编程实战手册
GitHub地址:https://github.com/xkzhangsan/java-concurrent-practice