java 多线程 6 : 同步锁(Lock)

本文介绍如何使用 Java 中的 ReentrantLock 来实现线程安全操作,通过示例展示了如何在银行账户取款操作中使用 ReentrantLock 来确保线程安全。

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("\t余额为:" + 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();
    }
}

 

转载于:https://www.cnblogs.com/Uzai/p/9675717.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值