主题思想:利用AtomicReference自带的CAS机制,实现类似于ReentrantLock的锁,当前线程进入时,CAS验证是否有其他线程持有锁,为null则让当前线程持有,不为null,线程自旋。解锁同理将持有线程置为NULL即可。
package com.zcy.controller;
import lombok.extern.slf4j.Slf4j;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicReference;
/**
* @Author zhangchongyu
* @Description
* @Date
*/
@Slf4j
public class AtomicReferenceDemo {
public static void main(String[] args) {
MyLock myLock = new MyLock();
for (int i = 0; i < 4; i++) {
new Thread(()->{
myLock.myLock();
log.info(Thread.currentThread().getName()+"执行代码中。。。。");
myLock.myUnLock();
}).start();
}
}
static class MyLock{
AtomicReference atomicReference = new AtomicReference();
void myLock() {
Thread thread = Thread.currentThread();
while (!atomicReference.compareAndSet(null,thread)){ //自旋锁
}
log.info(thread.getName()+"=====>获得锁");
try {
TimeUnit.SECONDS.sleep(4); //模拟耗时
} catch (InterruptedException e) {
e.printStackTrace();
}
}
void myUnLock(){
Thread thread = Thread.currentThread();
atomicReference.compareAndSet(thread,null);
log.info(thread.getName()+"=====>释放锁");
}
}
}
运行结果如下,可简单实现锁机制