package com.xf.lock;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
public class ReentrantLockTest {
/**
* 用于控制账户安全的锁对象,保证账户只有一把锁
*/
private static final Lock myLock = new ReentrantLock();
static class User implements Runnable {
private String name; // 用户名
private MyCount myCount; // 所要操作的账户
private int iocash; // 操作的金额,有正负之分了
public User(String name, MyCount myCount, int iocash) {
this.name = name;
this.myCount = myCount;
this.iocash = iocash;
}
public void run() {
// 获取锁
myLock.lock();
// 执行现金业务
myCount.setCash(myCount.getCash() + iocash);
System.out.println(name + "操作" + myCount + "账户成功,金额为" + iocash
+ ",当前金额为" + myCount.getCash());
// 释放锁,否则别的线程没有机会执行了
myLock.unlock();
}
}
/**
* 信用卡账户,可随意透支
*/
static class MyCount {
private String oid; // 账号
private int cash; // 账户余额
MyCount(String oid, int cash) {
this.oid = oid;
this.cash = cash;
}
public String getOid() {
return oid;
}
public void setOid(String oid) {
this.oid = oid;
}
public int getCash() {
return cash;
}
public void setCash(int cash) {
this.cash = cash;
}
@Override
public String toString() {
return "MyCount{" + "oid='" + oid + '\'' + ", cash=" + cash + '}';
}
}
/**
* 测试类
*/
static class Test {
public static void main(String[] args) {
// 创建并发访问的账户
MyCount myCount = new MyCount("张三的账户", 10);
// 创建一个线程池
ExecutorService pool = Executors.newCachedThreadPool();
// 创建一些并发访问用户,一个信用卡,存的存,取的取,好热闹啊
User u1 = new User("张三", myCount, -4);
User u2 = new User("李四", myCount, 6);
User u3 = new User("王五", myCount, -8);
User u4 = new User("赵六", myCount, 6);
// 在线程池中执行各个用户的操作
pool.execute(u1);
pool.execute(u2);
pool.execute(u3);
pool.execute(u4);
// 关闭线程池
pool.shutdown();
}
}
}