欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

自旋锁入门

程序员文章站 2022-07-10 17:30:17
自旋锁Demopublic class Spinlock { AtomicReference serialNumber = new AtomicReference(); public void LockMe() { Thread thread = Thread.currentThread(); System.out.println(thread.getName() + "加锁"); while (!serialNumber.compareAn...

自旋锁Demo

public class Spinlock {
    AtomicReference serialNumber = new AtomicReference();
    public void LockMe() {
        Thread thread = Thread.currentThread();
        System.out.println(thread.getName() + "加锁");
        while (!serialNumber.compareAndSet(null, thread)) {
        }
    }
    public void unLockMe() {
        Thread thread = Thread.currentThread();
        System.out.println(thread.getName() + "解锁");
        serialNumber.compareAndSet(thread, null);
    }
}

  public static void main(String[] args) throws Exception {
        Spinlock spinlock = new Spinlock();
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    spinlock.LockMe();
                    TimeUnit.SECONDS.sleep(5);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                } finally {
                    spinlock.unLockMe();
                }
            }
        }, "A").start();
        TimeUnit.SECONDS.sleep(1);
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    spinlock.LockMe();
                } finally {
                    spinlock.unLockMe();
                }
            }
        }, "B").start();
    }
A加锁
B加锁 //等待一段时间
A解锁
B解锁  
尝试获取锁的线程不会立即阻塞,而是采用循环的方式去尝试获取锁。
目的:减少线程上下文频繁的切换而引起的性能损耗,所以才自旋让当前线程一直占用资源。
好处:循环比较获取直到成功为止,没有类似wait()的阻塞。
缺点: 是循环会消耗CPU资源

本文地址:https://blog.csdn.net/qq_40721300/article/details/110230992

相关标签: 多线程