欢迎访问悦橙教程(wld5.com),关注java教程。悦橙教程  java问答|  每日更新
页面导航 : > > 文章正文

JAVA小学生——java锁之自旋锁,

来源: javaer 分享于  点击 37058 次 点评:65

JAVA小学生——java锁之自旋锁,


1. 什么是自旋锁

image.png

一个毕竟糙的例子就是好比上厕所,假设A先进去锁了门,这时B来了,如果B什么也不干,傻傻的一直站在门口等待,这时候B就被阻塞了。如果是自旋锁,B就会玩玩手机or来回踱步,然后问一下A:“好了没有?”,如果A回答不行,那就B继续玩手机然后再问 “好了没有?”,直到成功。

image.png

2.手写一个自旋锁

class MySpinLock {

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

    public void myLock() {
        Thread thread = Thread.currentThread();
        System.out.println(thread.getName() + "\t come ");
        while (!atomicReference.compareAndSet(null, thread)) {

        }
        System.out.println(thread.getName() + "\t locked ");

    }

    public void myUnlock() {
        Thread thread = Thread.currentThread();
        atomicReference.compareAndSet(thread, null);
        System.out.println(thread.getName() + "\t unlock");
    }


}


public class SpinLockDemo {


    public static void main(String[] args) throws InterruptedException {
        MySpinLock spinLock = new MySpinLock();
        new Thread(() -> {
            spinLock.myLock();

            try {
                TimeUnit.SECONDS.sleep(5);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            spinLock.myUnlock();
        }, "AA").start();

        TimeUnit.SECONDS.sleep(1);

        new Thread(() -> {
            spinLock.myLock();
        }, "BB").start();

    }
}

转载于:https://www.jianshu.com/p/905d38fef987

相关文章

    暂无相关文章
相关栏目:

用户点评