Java多线程--自旋锁

自旋锁,是指不会阻塞当前线程,而是采用循环的方式去获取锁,这样的话减少上下文切换,但是同时会消耗CPU资源。

    //---------------------------自旋锁-----------------------
    private static AtomicReference<Thread> atomicReference=new AtomicReference<>(null);

    public void lock(){
        //自旋
        while(!atomicReference.compareAndSet(null,Thread.currentThread())){
        }
    }

    public void unluck(){
        //自旋
        while(!atomicReference.compareAndSet(Thread.currentThread(),null)){
        }
    }

    @Test
    public void test07() throws InterruptedException {
        Thread thread01=new Thread(new Runnable() {
            @Override
            public void run() {
                System.out.println(Thread.currentThread().getName()+":尝试获取锁");
                lock();
                System.out.println(Thread.currentThread().getName()+":获取到锁");
                try {
                    Thread.sleep(5000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                System.out.println(Thread.currentThread().getName()+":开始释放锁");
                unluck();
                System.out.println(Thread.currentThread().getName()+":释放锁完成");
            }
        });
        thread01.setName("T1");
        thread01.start();

        Thread.sleep(1000);

        Thread thread02=new Thread(new Runnable() {
            @Override
            public void run() {
                System.out.println(Thread.currentThread().getName()+":尝试获取锁");
                lock();
                System.out.println(Thread.currentThread().getName()+":获取到锁");
                try {
                    Thread.sleep(3000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                System.out.println(Thread.currentThread().getName()+":开始释放锁");
                unluck();
                System.out.println(Thread.currentThread().getName()+":释放锁完成");
            }
        });
        thread02.setName("T2");
        thread02.start();

        while (Thread.activeCount()>2){}
        System.out.println("run over");
    }

核心原理为利用原子更新引用。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值