银行账户类:
package com.lovo; /** * 银行账户 * @author 骆昊 * */ public class Account { private double balance; // 账户余额 /** * 存款 * @param money 存入金额 */ public void deposit(double money) { double newBalance = balance + money; try { Thread.sleep(10); // 模拟此业务需要一段处理时间 } catch(InterruptedException ex) { ex.printStackTrace(); } balance = newBalance; } /** * 获得账户余额 */ public double getBalance() { return balance; } }
package com.lovo; /** * 存钱线程 * @author 骆昊 * */ public class AddMoneyThread implements Runnable { private Account account; // 存入账户 private double money; // 存入金额 public AddMoneyThread(Account account, double money) { this.account = account; this.money = money; } @Override public void run() { account.deposit(money); } }测试类:
package com.lovo; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; public class Test01 { public static void main(String[] args) { Account account = new Account(); ExecutorService service = Executors.newFixedThreadPool(100); for(int i = 1; i <= 100; i++) { service.execute(new AddMoneyThread(account, 1)); } service.shutdown(); while(!service.isTerminated()) {} System.out.println("账户余额: " + account.getBalance()); } }
package com.lovo; /** * 银行账户 * @author 骆昊 * */ public class Account { private double balance; // 账户余额 /** * 存款 * @param money 存入金额 */ public synchronized void deposit(double money) { double newBalance = balance + money; try { Thread.sleep(10); // 模拟此业务需要一段处理时间 } catch(InterruptedException ex) { ex.printStackTrace(); } balance = newBalance; } /** * 获得账户余额 */ public double getBalance() { return balance; } }
package com.lovo; /** * 存钱线程 * @author 骆昊 * */ public class AddMoneyThread implements Runnable { private Account account; // 存入账户 private double money; // 存入金额 public AddMoneyThread(Account account, double money) { this.account = account; this.money = money; } @Override public void run() { synchronized (account) { account.deposit(money); } } }3. 通过JDK 1.5显示的锁机制,为每个银行账户创建一个锁对象,在存款操作进行加锁和解锁的操作
package com.lovo; import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReentrantLock; /** * 银行账户 * * @author 骆昊 * */ public class Account { private Lock accountLock = new ReentrantLock(); private double balance; // 账户余额 /** * 存款 * * @param money * 存入金额 */ public void deposit(double money) { accountLock.lock(); try { double newBalance = balance + money; try { Thread.sleep(10); // 模拟此业务需要一段处理时间 } catch (InterruptedException ex) { ex.printStackTrace(); } balance = newBalance; } finally { accountLock.unlock(); } } /** * 获得账户余额 */ public double getBalance() { return balance; } }按照上述三种方式对代码进行修改后,重写执行测试代码Test01,将看到最终的账户余额为100元。