Java并发编程JUC之手写自旋锁

自旋锁:spinlock,是指尝试获取锁的线程不会立即阻塞,而是采用循环的方式去尝试获取锁,这样的好处是减少线程上下文切换的消耗,缺点是循环会消耗CPU

原来提到的比较并交换,底层使用的就是自旋,自旋就是多次尝试,多次访问,不会阻塞的状态就是自旋。

/**
 * 自旋锁
 */
public class SpinLockDemo {


    AtomicReference atomicReference = new AtomicReference();

    public void myLock() {
        Thread thread = Thread.currentThread();
        System.out.println(Thread.currentThread() + " come in!");

        while (!atomicReference.compareAndSet(null, thread)) {
//            System.out.println("正在持有锁。。。。,ThreadName: "+Thread.currentThread());
        }
    }


    public void myUnLock() {
        Thread thread = Thread.currentThread();

        atomicReference.compareAndSet(thread, null);

        System.out.println(Thread.currentThread() + " invoked myUnLock!");
    }


    public static void main(String[] args) {
        SpinLockDemo spinLockDemo = new SpinLockDemo();


        Thread t1 = new Thread(new Runnable() {
            @Override
            public void run() {
                spinLockDemo.myLock();
                try {
                    TimeUnit.SECONDS.sleep(5);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                spinLockDemo.myUnLock();
            }
        });

        t1.setName("t1");
        t1.start();

        try {
            TimeUnit.SECONDS.sleep(1);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }


        Thread t2 = new Thread(new Runnable() {
            @Override
            public void run() {
                spinLockDemo.myLock();
                spinLockDemo.myUnLock();
            }
        });

        t2.setName("t2");
        t2.start();
    }


}

 

你可能感兴趣的:(多线程,多线程)