Java自定义实现自旋锁

以下是通过尚硅谷-周阳老师对自旋锁的讲解,自己自定义实现的自旋锁

import java.util.concurrent.atomic.AtomicReference;

/**
* 通过CAS操作完成自旋锁,t1线程先进来调用lock方法,自己持有锁3秒钟,t2线程随后进来发现
* 当前有线程持有锁,不是null,所以只能通过自旋等待,直到t1释放锁后,t2再抢到锁
*/
public class SpinLockDemo {

    AtomicReference<Thread> atomicReference = new AtomicReference<>();

    public void lock() {
        Thread thread = Thread.currentThread();
        System.out.println(Thread.currentThread().getName() + "准备加锁...");
        while (!atomicReference.compareAndSet(null, thread)) {
            System.out.println(Thread.currentThread().getName() + "一直自旋,直到获得锁...");
        }
        System.out.println(Thread.currentThread().getName() + "退出..");
    }

    public void unLock() {
        Thread thread = Thread.currentThread();
        System.out.println(Thread.currentThread().getName() + "释放锁...");
        atomicReference.compareAndSet(thread, null);
    }

    public static void main(String[] args) throws InterruptedException {

        SpinLockDemo spinLockDemo = new SpinLockDemo();
        new Thread(() -> {
            spinLockDemo.lock();
            try {
                Thread.sleep(3000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            spinLockDemo.unLock();
        }, "t1").start();

        Thread.sleep(2000);

        new Thread(() -> {
            spinLockDemo.lock();
            try {
                Thread.sleep(2000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            spinLockDemo.unLock();
        }, "t2").start();
    }
}

AtomicReference: 原子引用线程

自旋锁概念:是指尝试获取锁的线程不会立即阻塞,而是采用循环的方式去尝试获取锁,这样的好处是减少线程上下文切换的消耗,缺点是循环会消耗CPU。

自旋锁优点: 循环比较获取锁,直到成功为止,没有类似wait()的阻塞。

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值