Lock锁
为了更清晰的表达如何加锁和释放锁,JDK5以后提供了一个新的锁对象Lock,更加灵活、方便。
Lock实现提供比使用synchronized方法和语句可以获得更广泛的锁定操作。
Lock是接口不能直接实例化,这里采用它的实现类ReentrantLock来构建Lock锁对象。
方法名称:
public ReentrantLock()
说明:
获得Lock锁的实现类对象。
Lock的API
void lock() 获得锁
void unlock() 释放锁
看一下演示代码:
public class ThreadDemo5 {
//模拟取钱案例
public static void main(String[] args) {
Accout acc=new Accout("ICBC-111",100000);
new DrawThread(acc,"小明").start();
new DrawThread(acc,"小红").start();
}
}
public class DrawThread extends Thread {
private Accout acc;
public DrawThread(Accout acc, String name) {
super(name);
this.acc = acc;
}
@Override
public void run() {
//取钱的
acc.drawMoney(100000);
}
}
public class Accout{
private String cardId;
private double money;
private Lock lock=new ReentrantLock();
public String getCardId() {
return cardId;
}
public void setCardId(String cardId) {
this.cardId = cardId;
}
public double getMoney() {
return money;
}
public void setMoney(double money) {
this.money = money;
}
public Accout(String cardId, double money) {
this.cardId = cardId;
this.money = money;
}
public Accout() {
}
public String toString() {
return "Accout{cardId = " + cardId + ", money = " + money + "}";
}
public void drawMoney(double money) {
//先获取是谁来取钱,现成的名字就是人名
String name =Thread.currentThread().getName();
//判断账户是否够钱
lock.lock();//上锁
try {
if (this.money >= money) {
//取钱
System.out.println(name + "来取钱成功,吐出"+money);
//更新余额
this.money -= money;
System.out.println(name + "取钱后剩余:"+this.money);
}else {
System.out.println(name + "来取钱,余额不足!");
}
} finally {
lock.unlock();//释放锁
}
}
}
版权声明:本文为weixin_46782084原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。