您好,欢迎来到三六零分类信息网!老站,搜索引擎当天收录,欢迎发信息

java怎么实现可重入的自旋锁

2024/3/17 1:01:39发布36次查看
说明
1、是指试图获得锁的线程不会堵塞,而是通过循环获得锁。
2、优点:减少上下文切换的消耗。
缺点:循环消耗cpu。
实例
public class reentrantspinlock {      private atomicreference<thread> owner = new atomicreference<>();     // 可重入次数    private int count = 0;     // 加锁    public void lock() {        thread current = thread.currentthread();        if (owner.get() == current) {            count++;            return;        }        while (!owner.compareandset(null, current)) {            system.out.println(--我在自旋--);        }    }     //解锁    public void unlock() {        thread current = thread.currentthread();        //只有持有锁的线程才能解锁        if (owner.get() == current) {            if (count > 0) {                count--;            } else {                //此处无需cas操作,因为没有竞争,因为只有线程持有者才能解锁                owner.set(null);            }        }    }     public static void main(string[] args) {        reentrantspinlock spinlock = new reentrantspinlock();        runnable runnable = () -> {            system.out.println(thread.currentthread().getname() + 开始尝试获取自旋锁);            spinlock.lock();            try {                system.out.println(thread.currentthread().getname() + 获取到了自旋锁);                thread.sleep(4000);            } catch (interruptedexception e) {                e.printstacktrace();            } finally {                spinlock.unlock();                system.out.println(thread.currentthread().getname() + 释放了了自旋锁);            }        };        thread thread1 = new thread(runnable);        thread thread2 = new thread(runnable);        thread1.start();        thread2.start();    }}
以上就是java怎么实现可重入的自旋锁的详细内容。
该用户其它信息

VIP推荐

免费发布信息,免费发布B2B信息网站平台 - 三六零分类信息网 沪ICP备09012988号-2
企业名录 Product