ReentrantLock——公平锁与非公平锁对比

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/lhc2207221755/article/details/83588380
 /**
     * 公平锁非公平锁
     */
    @Test
    public void FairLockAndNotFairLockTest() throws Exception {
        ReentrantLock2 fairLock = new ReentrantLock2(true);
        ReentrantLock2 unFairLock = new ReentrantLock2(false);

        testLock("公平锁",fairLock);

        testLock("非公平锁", unFairLock);

    }

    class Job extends Thread {
        private Lock lock;

        Job(Lock lock) {
            this.lock = lock;
        }

        @Override
        public void run() {
            for (int i = 0; i < 2; i++) {
                lock.lock();
                try {
                    Thread.sleep(1000);
                    System.out.println("current thread name : "
                            + Thread.currentThread().getName()
                            + "  ; 同步队列中的线程 :"
                            + ((ReentrantLock2) lock).getQueuedThreads());
                } catch (Exception e) {
                    System.out.println(e);
                } finally {
                    lock.unlock();
                }
            }
        }
    }

    private void testLock(String type, Lock lock) throws InterruptedException {
        System.out.println(type);
        for (int i = 0; i < 5; i++) {
            Thread thread = new Thread(new Job(lock)) {
                public String toString() {
                    return getName();
                }
            };
            thread.setName("" + i);
            thread.start();
        }
        Thread.sleep(11000);
    }


    public class ReentrantLock2 extends ReentrantLock {
        ReentrantLock2(boolean fair) {
            super(fair);
        }
        /**
         * 获取等待锁线程列表
         *
         * @return
         */
        public Collection<Thread> getQueuedThreads() {
            List<Thread> threads = new ArrayList<>(super.getQueuedThreads());
            Collections.reverse(threads);
            return threads;
        }

    }

总结:

  • 总体来说,公平锁需要更多的线程切换,整体上性能不如非公平锁好。

猜你喜欢

转载自blog.csdn.net/lhc2207221755/article/details/83588380