用Java原子变量的CAS方法实现一个自旋锁

实现:

复制代码
package sjq.mylock;

import java.util.concurrent.atomic.AtomicReference;

public class SpinLock { private AtomicReference<Thread> owner = new AtomicReference<>(); //不调用有参构造函数,则实例为null public void lock(){ Thread currentThread = Thread.currentThread(); while(!owner.compareAndSet(null, currentThread)){ // owner == null ,则compareAndSet返回true,否则为false。 //拿不到owner的线程,不断的在死循环  } } public void unLock(){ owner.set(null); // 也可以这样写,太麻烦,没必要 /* Thread cur = Thread.currentThread(); owner.compareAndSet(cur, null); */ } }
复制代码

 

 

测试:

复制代码
package sjq.mylock;

import java.util.concurrent.CountDownLatch;

import org.junit.Test; public class TestSpinLock { final static int THREAD_NUM = 100; static int x = 0; @Test public void testLock() throws InterruptedException { CountDownLatch latch = new CountDownLatch(THREAD_NUM); // 锁 SpinLock spinLock = new SpinLock(); for (int i = 0; i < THREAD_NUM; i++) { // 启动子线程 new Thread(() -> { // 每个线程循环多次,频繁上锁,解锁。 for (int n = 0; n < 100; n++) { spinLock.lock(); x++; spinLock.unLock(); } latch.countDown(); // 子线程通知主线程,工作完毕。  }).start(); } latch.await(); // 主线程等待所有子线程结束。  System.out.println(x); // 最终打印结果:10000 ,未出现线程不安全的异常。  } }
复制代码

 

 轉自 https://www.cnblogs.com/shijiaqi1066/p/5999610.html

 

转载于:https://www.cnblogs.com/tiancai/p/8807909.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值