java5开始可以显示定义同步锁对象来实现同步,这种机制下,同步锁由对象充当
Lock比同步代码块和同步方法更加灵活
在实现线程安全的机制中,比较常用的是ReentrantLock(可重入锁)。使用该Lock对象可以显示的加锁,释放锁
ReentrantLock 代码格式如下:
class X{ //定义锁对象 private final ReentrantLock lock = new ReentrantLock(); //... //定义需要保证线程安全的方法 public void method() { //加锁 lock.lock(); try { //需要保证线程安全的代码 } finally {//使用finally来保证释放锁 lock.unlock(); } } }
public class Account { private String account;//账号 private double balance;//余额 //定义锁对象 private final ReentrantLock lock = new ReentrantLock(); public Account() { super(); } public Account(String account, double balance) { super(); this.account = account; this.balance = balance; } public void drawMoney(double drawMoney) { //加锁 lock.lock(); try { if(balance >= drawMoney) { System.out.println(Thread.currentThread().getName() + "取钱成功!吐出钞票:" + drawMoney); try { Thread.sleep(1); } catch (InterruptedException e) { e.printStackTrace(); } balance -= drawMoney; System.out.println(" 余额为:" + balance); }else { System.out.println(Thread.currentThread().getName() + "取钱失败!余额不足"); } } finally {//放锁 lock.unlock(); } } public String getAccount() { return account; } public void setAccount(String account) { this.account = account; } public double getBalance() { return balance; } public void setBalance(double balance) { this.balance = balance; } }
public class DrawThread extends Thread{ private Account account;//模拟账户 private double drawMoney;//当前取钱线程想要取的钱数 public DrawThread(String name , Account account, double drawMoney) { super(name); this.account = account; this.drawMoney = drawMoney; } public void run() { account.drawMoney(drawMoney); } public static void main(String[] args) { Account account = new Account("123456" , 1000); new DrawThread("A", account, 800).start(); new DrawThread("B", account, 800).start(); } }