首页 > 其他分享 >公平锁和非公平锁的性能对比

公平锁和非公平锁的性能对比

时间:2022-10-22 17:22:36浏览次数:44  
标签:info log int 性能 start ticketCount 公平 对比

写在最前面:

默认看到这的大神们都懂什么是公平锁和非公平锁

废话不多说,直接上代码:

package org.sino.multith.lock;

import lombok.extern.slf4j.Slf4j;
import org.sino.util.ThreadUtil;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.locks.ReentrantLock;

/**
 * 案例说明:
 * 使用公平锁和非公平锁进行3个售票员(3线程)卖10w张票所需的时间
 *
 */
@Slf4j
public class FairUnFairDemo {
    static ExecutorService executorService = ThreadUtil.newCpuThreadPool();

    public static void main(String[] args) throws InterruptedException {
        int ticketCount = 100000;
        int threadCount = 12;

        Ticket fairTicket = new Ticket(ticketCount, Boolean.TRUE);
        CountDownLatch fairCdl = new CountDownLatch(threadCount);
        log.info("------------------------------- 公平锁开始 ----------------------------------------");
        long start = System.currentTimeMillis();
        for (int i = 1; i <= threadCount; i++) {
            new Thread(()->{
                while(fairTicket.sale()) {

                }
                fairCdl.countDown();
            }, "FairLock" + i).start();
        }
        fairCdl.await(); 
        long end = System.currentTimeMillis();
     log.info("一共耗费:" + (end - start) + " ms"); log.info("------------------------------- 公平锁结束 ----------------------------------------"); Ticket unfairTicket = new Ticket(ticketCount, Boolean.FALSE); CountDownLatch unfairCdl = new CountDownLatch(threadCount); log.info("------------------------------- 非公平锁开始 ----------------------------------------"); start = System.currentTimeMillis(); for (int i = 1; i <= threadCount; i++) { new Thread(()->{ while (unfairTicket.sale()) { } unfairCdl.countDown(); }, "UnFairLock" + i).start(); } unfairCdl.await(); end = System.currentTimeMillis();
     log.info("一共耗费:" + (end - start) + " ms"); log.info("------------------------------- 非公平锁开始 ----------------------------------------"); } } @Slf4j class Ticket { private int ticketCount; private ReentrantLock lock; public Ticket(int ticketCount, boolean fair) { this.ticketCount = ticketCount; // false为非公平锁,true为公平锁 this.lock = new ReentrantLock(fair); } /** * 还有票,返回true,没票了返回false * * @return */ public boolean sale () { lock.lock(); try { if(ticketCount > 0) { ticketCount --; // log.info(" --> 卖出第:\t" + (ticketCount --) + " 还剩下:" + ticketCount); } if(ticketCount == 0) { // log.info(" --> \t还剩下:" + ticketCount); } return ticketCount != 0; } finally { lock.unlock(); } } }

运行结果:

在10w票的运行结果:

 

 在100w票的运行结果:

 

  在1000w票的运行结果:

 

 

结论:

在高并发的场景下,公平锁的性能远低于非公平锁

标签:info,log,int,性能,start,ticketCount,公平,对比
From: https://www.cnblogs.com/sinoknots/p/16816706.html

相关文章