Java简单实现一个自旋锁

版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://blog.csdn.net/kaikai_sk/article/details/79238771

SpinLock.java

package com.sk.spinlock;

import java.util.concurrent.atomic.AtomicReference;

public class SpinLock
{
    //Java中的原子操作(CAS)
    //持有自旋锁的线程对象
    AtomicReference<Thread> owner=new AtomicReference<Thread>();
    private int count;

    public void lock()
    {
        Thread curThread=Thread.currentThread();
        //lock函数将owner设置为当前线程,并且预测原来的值为空
        //当有第二个线程调用lock操作时由于owner的值不为空,导致循环
        //一直被执行,直至第一个线程调用unclock函数将owner设置为null,第二个线程才能进入临界区
        while(!owner.compareAndSet(null, curThread))
        {

        }
    }

    //unlock将owner的值设置为null,并且预测值为当前线程
    public void unlock()
    {
        Thread cur=Thread.currentThread();
        owner.compareAndSet(cur, null);
    }

}

LockTest .java

package com.sk.spinlock;

public class LockTest implements Runnable
{
    static int sum;
    private SpinLock lock;

    public LockTest(SpinLock lock)
    {
        this.lock=lock;
    }

    public static void main(String[] args) throws Exception
    {
        SpinLock lock=new SpinLock();
        for(int i=0;i<100;i++)
        {
            LockTest test=new LockTest(lock);
            Thread t=new Thread(test);
            t.start();
        }
        Thread.currentThread().sleep(1000);
        System.out.println(sum);
    }

    @Override
    public void run()
    {
        this.lock.lock();
        sum++;
        this.lock.unlock();
    }

}
展开阅读全文

没有更多推荐了,返回首页