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");
    }

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

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章