ReentrantLock的公平锁和非公平锁测试

公平锁:会按照线程启动的顺序,根据队列排序执行;非公平锁:新启动的线程有一定概率抢到刚释放的锁。

测试1

package practice.reentrantlock;

import java.util.concurrent.locks.ReentrantLock;

/**
 * ReentrantLock公平锁和非公平锁测试1
 * @author lbw
 * @version 1.0
 * @date 2020/11/25 11:28
 */
public class ReentrantLockTest {
    //true公平锁;false非公平锁:执行到47时,有一定概率抢到31执行后的锁
    static ReentrantLock reentrantLock = new ReentrantLock(true);
    public static void main(String[] args) throws InterruptedException {
        for(int i = 1; i < 51; i ++){
            int finalI = i;
            new Thread(() -> {
                running("t" + finalI);
            },"t" + finalI).start();
            Thread.sleep(1);
        }
    }
    private static void running(String threadName){
        reentrantLock.lock();
        System.out.println(threadName + "...");
        try {
            Thread.sleep(2);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }finally {
            reentrantLock.unlock();
        }
    }
}

测试1执行结果

说明:每个线程启动后sleep了1毫秒,所以线程启动有序的
1.当new ReentrantLock(true)设置为true时,打印出的结果为有序的。
2.当new ReentrantLock(false)设置为false时,线程47有一定概率抢到线程31结束后的锁。
执行结果1

测试2

package practice.reentrantlock;

import java.util.concurrent.locks.ReentrantLock;

/**
 * ReentrantLock公平锁和非公平锁测试2
 * @author lbw
 * @version 1.0
 * @date 2020/11/25 11:28
 */
public class ReentrantLockTest {
    //true公平锁:会通过队列排队,执行running方法和线程启动顺序一致
    //false非公平锁:只要锁被释放,就会争抢。执行running方法和线程启动顺序不同
    static ReentrantLock reentrantLock = new ReentrantLock(true);
    public static void main(String[] args) throws InterruptedException {
        for(int i = 1; i < 51; i ++){
            int finalI = i;
            new Thread(() -> {
                System.out.println("开始启动线程" + finalI);
                running("t" + finalI);
            },"t" + finalI).start();
        }
    }
    private static void running(String threadName){
        reentrantLock.lock();
        System.out.println(threadName + "...");
        try {
            Thread.sleep(2);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }finally {
            reentrantLock.unlock();
        }
    }
}

测试2执行结果

1.当new ReentrantLock(true)设置为true时,running方法的执行和线程启动顺序一致。(都为2,3,1,4,5,7,8,9,10…)
执行结果2.1.1执行结果2.1.2

2.当new ReentrantLock(false)设置为false时,running方法和线程启动顺序不同。(线程启动顺序为:1,3,4,2,5,6,7,8,9,10…;running方法的执行顺序为:3,29,45,4,2,1,5,6,7,8,9,10…)
执行结果2.2.1
执行结果2.2.2

  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 3
    评论
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值