【JUC编程进阶】自旋锁

2021/6/2 20:21:11

本文主要是介绍【JUC编程进阶】自旋锁,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

自定义一个锁

package spinLock;

import day3.A;

import java.util.concurrent.atomic.AtomicReference;

/**
 * @author admin
 * @version 1.0.0
 * @ClassName demo1.java
 * @Description TODO
 * @createTime 2021年06月02日 19:37:00
 */
// 自旋锁
public class demo1 {
    // Thread 默认为null
    AtomicReference<Thread> atomicReference = new AtomicReference<>();

    // 加锁
    public void mylock(){
        Thread thread = Thread.currentThread();
        System.out.println(Thread.currentThread().getName()+"------>mylock");

        // 自旋锁
        while (!atomicReference.compareAndSet(null,thread)){

        }
    }



    // 解锁
    public void myUnlock(){
        Thread thread = Thread.currentThread();
        System.out.println(Thread.currentThread().getName()+"------>myUnlock");

      atomicReference.compareAndSet(thread,null);
    }
}


测试:

package spinLock;

import java.util.concurrent.TimeUnit;

/**
 * @author admin
 * @version 1.0.0
 * @ClassName Test.java
 * @Description TODO
 * @createTime 2021年06月02日 19:42:00
 */
public class Test {
    public static void main(String[] args) throws Exception{
        // 底层使用的自旋锁 CAS
        demo1 lock = new demo1();

        new Thread(()->{
            lock.mylock();
            try {
                TimeUnit.SECONDS.sleep(3);
            } catch (InterruptedException e) {
                e.printStackTrace();
            } finally {
                lock.myUnlock();
            }
        },"T1").start();
        TimeUnit.SECONDS.sleep(1);
        new Thread(()->{
            lock.mylock();
            try {
                TimeUnit.SECONDS.sleep(1);
            } catch (InterruptedException e) {
                e.printStackTrace();
            } finally {
                lock.myUnlock();
            }
        },"T2").start();
    }
}



这篇关于【JUC编程进阶】自旋锁的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!


扫一扫关注最新编程教程