仅用于测试学习,未实现可重入
实现
@Slf4j(topic = "c.six-Demo1")
class DiyCasLock{
//原子整数:标记锁的状态
private final AtomicInteger status=new AtomicInteger(0);
//线程对象:标记获得当前锁的线程
private volatile Thread current=null;
//加锁操作:CAS循环获取锁
public boolean lock(){
while (true){
if(status.compareAndSet(0, 1)){
current=Thread.currentThread();
log.debug("加锁成功");
break;
}
}
return true;
}
//解锁
public void unlock(){
//判断解锁操作的线程是否为拥有锁的线程
if(current!=Thread.currentThread()){
throw new RuntimeException("当前线程无法解锁!");
}
log.debug("解锁");
current=null;
status.set(0);
}
}
测试
public static void main(String[] args){
//1.创建锁对象
DiyCasLock diyCasLock=new DiyCasLock();
//2.创建线程
new Thread(()->{
//2.1 尝试获取锁
diyCasLock.lock();
try {
TimeUnit.SECONDS.sleep(1);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("t1运行");
//2.2 释放锁
diyCasLock.unlock();
},"t1").start();
//3.创建竞争锁的线程
new Thread(()->{
// diyCasLock.unlock(); //已处理解锁乱象
//3.1 尝试获取锁
diyCasLock.lock();
System.out.println("t2运行");
//3.2 释放锁
diyCasLock.unlock();
},"t2").start();
}
结果
正常加解锁
10:50:25 [t1] c.six-Demo1 - 加锁成功
t1运行
10:50:26 [t1] c.six-Demo1 - 解锁
10:50:26 [t2] c.six-Demo1 - 加锁成功
t2运行
10:50:26 [t2] c.six-Demo1 - 解锁
t2先尝试解开t1的锁
Exception in thread "t2" java.lang.RuntimeException: 当前线程无法解锁!
at com.example.create.six.DiyCasLock.unlock(Demo1.java:50)
at com.example.create.six.Demo1.lambda$main$1(Demo1.java:24)
at java.lang.Thread.run(Thread.java:748)
10:41:42 [t1] c.six-Demo1 - 加锁成功
t1运行
10:41:43 [t1] c.six-Demo1 - 解锁