import java.util.concurrent.atomic.AtomicLong;
import java.util.stream.IntStream;
public class AtomicLock {
//V 内存值 初始为0
private AtomicLong atomicLong = new AtomicLong(0);
private Thread lockCurrentThread;
private boolean result = false;
/**
* 获取锁
* @return 将内存值改为1
*/
public boolean myLock(){
//设置的初始值为0, expect 也为 0 也就是E 预期值 ,修改值为1 v==e 就会吧 v改为1
while(!result){
result = atomicLong.compareAndSet(0, 1);
System.out.println(Thread.currentThread().getName()+"线程没有获取到锁,等待释放锁");
}
if (result){
//修改成功后,则将该线程 持有锁
lockCurrentThread = Thread.currentThread();
}
return result;
}
/**
* 释放锁 将内存值改为0
* @return
*/
public boolean myUnLock(){
//如果该线程 不是上面 持有锁的线程 则 返回false
if (lockCurrentThread!=null &&lockCurrentThread!=Thread.currentThread()){
System.out.println(Thread.currentThread().getName()+":没有获取倒锁,无需释放锁");
return false;
}
boolean result = atomicLong.compareAndSet(1, 0);
System.out.println(Thread.currentThread().getName()+":释放锁");
return result;
}
//测试
public static void main(String[] args) {
AtomicLock atomicLock = new AtomicLock();
IntStream.range(1,3).forEach(i->{
new Thread(()->{
try{
boolean result = atomicLock.myLock();
if (result){
System.out.println(Thread.currentThread().getName()+":获取锁成功");
}else {
System.out.println(Thread.currentThread().getName()+":没有获取到锁");
}
}catch (Exception e){
e.printStackTrace();
atomicLock.myUnLock();
}finally {
atomicLock.myUnLock();
}
}).start();
});
}
}
cas自旋锁编写
最新推荐文章于 2022-11-03 12:30:13 发布